简体   繁体   中英

Vertically align span in a tag

So here is my markup. Solution has to work dynamically for a single line or double line in the span. So it should be css that can be added to each of these and work fine. From looking on the internez this seems to be impossible. Please prove me wrong.

<ul style="text-align:center; list-style-type: none;">
    <li style="width: 200px">
        <a href="http://www.bing.com" style="display: block; height:35px; background: Black;">
            <span>Vertical Align This Text</span>
        </a>
    </li>
</ul>

<ul style="text-align:center; list-style-type: none;">
    <li style="width: 200px">
        <a href="http://www.bing.com" style="display: block; height:35px; background: Black;">
            <span>Vertical Align This Text With Double Line As Well</span>
        </a>
    </li>
</ul>

This works for me:

<ul style="text-align:center; list-style-type: none;">
    <li style="width: 200px; display: table">
        <a href="http://www.bing.com" style="display: table-cell; height:35px; background: Black; vertical-align: middle; text-align:center">
            <span>Vertical Align This Text</span>
        </a>
    </li>
</ul>

<ul style="text-align:center; list-style-type: none;">
    <li style="width: 200px; display: table">
        <a href="http://www.bing.com" style="display: table-cell; height:35px; background: Black; vertical-align: middle; text-align:center">
            <span>Vertical Align This Text With Double Line As Well</span>
        </a>
    </li>
</ul>

CSS code for convenience:

ul {
  list-style-type: none;
}

li {
  width: 200px;
  display: table;
}

a {
  display: table-cell;
  height: 35px;
  background: black;
  vertical-align: middle;
  text-align: center;
}

Since your containing <a> have a set height value, you can use the ol' line-height trick of setting it to the same value, in this case:

a { 
    height:35px; 
    line-height:35px; 
}

This will only work, though, if your <span> isn't wider than your <li> . In the case with the double line, you'd need to set the <line-height> to half the <a> 's height ( 35px height divided by 2 lines), so around 17px. If you had three lines, it would work with 35px/3 ~ 11px. But as you can imagine, it will look smooshed at one point. So depending on the content you might have to with the relative/absolute positioning, a smaller font, or just less content ;)

Give your <li> and <a> the following CSS properties

li{
  position:relative;
}

a{
  position:absolute;
  top:50%;
  margin-top:-17px; /*negative half of your <a> tag height */
}

Check working example at http://jsfiddle.net/r4Wsx/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM