CSS vertical alignment of inline/inline-block elements

HtmlCssVertical Alignment

Html Problem Overview


I'm trying to get several inline and inline-block components aligned vertically in a div. How come the span in this example insists on being pushed down? I've tried both vertical-align:middle; and vertical-align:top;, but nothing changes.

HTML:

<div>
  <a></a><a></a>
  <span>Some text</span>
</div>​

CSS:

a {
    background-color:#FFF;
    width:20px;
    height:20px;
    display:inline-block;
    border:solid black 1px;
}

div {
    background:yellow;
    vertical-align:middle;
}
span {
    background:red;
}

RESULT:
enter image description here

FIDDLE

Html Solutions


Solution 1 - Html

vertical-align applies to the elements being aligned, not their parent element. To vertically align the div's children, do this instead:

div > * {
    vertical-align:middle;  // Align children to middle of line
}

See: http://jsfiddle.net/dfmx123/TFPx8/1186/

NOTE: vertical-align is relative to the current text line, not the full height of the parent div. If you wanted the parent div to be taller and still have the elements vertically centered, set the div's line-height property instead of its height. Follow jsfiddle link above for an example.

Solution 2 - Html

Give vertical-align:top; in a & span. Like this:

a, span{
 vertical-align:top;
}

Check this http://jsfiddle.net/TFPx8/10/

Solution 3 - Html

Simply floating both elements left achieves the same result.

div {
background:yellow;
vertical-align:middle;
margin:10px;
}

a {
background-color:#FFF;
width:20px;
height:20px;
display:inline-block;
border:solid black 1px;
float:left;
}

span {
background:red;
display:inline-block;
float:left;
}

Solution 4 - Html

For fine tuning the position of an inline-block item, use top and left:

  position: relative;
  top: 5px;
  left: 5px;

Thanks CSS-Tricks!

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionYarinView Question on Stackoverflow
Solution 1 - HtmlDiegoView Answer on Stackoverflow
Solution 2 - HtmlsandeepView Answer on Stackoverflow
Solution 3 - HtmlHoldTheLineView Answer on Stackoverflow
Solution 4 - HtmlkslstnView Answer on Stackoverflow