Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

CSS

Centering text within SVG?

Hi there.

I'd like to center an h2 (x and y) within my SVG. I've tried display:table, display:table-cell, vertical-align: middle, and giving the h2 a negative top-margin but none of these methods seem to work. The h2 either sits at the bottom of my SVG or aligns itself next to it but nowhere inside of it, unless the'res a negative top margin. Here's the HTML:

    <div class="second">
      <?xml version="1.0" encoding="utf-8"?>
      <!-- Generator: Adobe Illustrator 16.0.0, SVG Export Plug-In . SVG Version: 6.00 Build 0)  -->
      <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
      <svg version="1.1" id="poly" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
          viewBox="0 0 119 47.829" enable-background="new 0 0 119 47.829" xml:space="preserve">
      <polygon class='poly' fill="none" stroke="#FFFFFF" stroke-miterlimit="10" points="117.5,3.829 1.5,3.829 24.7,47.829 94.3,47.829 "/>
      </svg>
      <h2> ABOUT </h2>
    </div>

I'd like it to be fluid, but I'm not sure how to execute that either. Media-queries?

I think a easy way will be to use this css

h2 { text-align: center; position: absolute; width: 100%; top: 50vh; z-index: 999; }

Then the h2 is over the svg and the alignment is focus on your browser only.

Thanks Meik for replying though once I resize my window the text goes wandering off. I'm guessing position: absolute is the reason for this.

1 Answer

.second {
   position: relative;
}

.second h2 {
    position: absolute;
   top:0; bottom:0; left:0; right:0;
   margin:auto
}