问题
I'd like to center a span element inside a h1 tag. I tried to to set a line-height but it seems to center only the span but not the text next to it. Note: I probably can't use position absolute as the "icon" is not displayed always and it can have different widths.
See the fiddle I've created: http://jsfiddle.net/JJhCY/1/
html:
<h1>
<span class="icon">Icon</span>
Some Text related to the icon
</h1>
CSS:
.icon
{
background: aqua;
border: 1px solid blue;
font-size: 80%;
border-radius: 3px;
width: 40px;
line-height: 13px;
padding: 2px;
display: inline-block;
text-align: center;
}
h1
{
background: red;
font-size: 11px;
line-height: 18px;
}
any idea?
回答1:
Your CSS basically works. It is more obvious if you increase the line-height:
see demo at http://jsfiddle.net/audetwebdesign/PUeaY/
h1 {
background: red;
font-size: 40px;
line-height: 80px;
}
.icon {
background: aqua;
border: 1px solid blue;
border-radius: 3px;
padding: 0px 4px;
width: auto;
display: inline-block;
font-size: 20px;
line-height: 40px;
vertical-align: 7px;
}
In this example, both the span and the text are vertically aligned in the center, which I think is what you want.
How This Works...
The CSS engine uses the vertical-align property to align the baseline of the text segments.
In this case, I set the default font-size and line-height for h1
to 40px and 80px respectively.
For the .icon
, I reduce the font-size and line-height by 50%. If vertical-align
were set to baseline
or 0
, both the smaller and the larger text would align along the bottom of the letters, but it would not look centered because the icon text has a smaller font size.
By adjusting vertical-align
to 7px, I got a centering that looks pretty good. This is not exactly a precise process, but it may work well enough.
回答2:
Another easy way to achieve this would be to use negative margins.
span{margin:-4px 10px 0 0} // Uses order of top, right, bottom, left
来源:https://stackoverflow.com/questions/18616621/center-span-text-vertically-inside-h1