150

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

web-tiki
  • 87,261
  • 27
  • 200
  • 230
Yarin
  • 144,097
  • 139
  • 361
  • 489

4 Answers4

283

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.

Diego
  • 16,895
  • 5
  • 56
  • 64
  • This stops working if you specify a height for the outer `div`. – Abhranil Das May 28 '15 at 20:26
  • 4
    @AbhranilDas `vertical-align` is relative to the current text line, not the parent element. To make this work as you want, set the div's `line-height` instead of its `height`. – Diego May 29 '15 at 22:18
25

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

a, span{
 vertical-align:top;
}

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

sandeep
  • 85,904
  • 23
  • 131
  • 151
6

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;
}
HoldTheLine
  • 122
  • 3
  • 14
  • The problem with floating them to the left is that they will wrap to the next line when the browser gets too small. Sometimes you need items to stay inline even beyond the browser bounds and thus, `inline-block` is the only solution. – Jake Wilson Feb 13 '13 at 19:10
  • While that wrapping problem can be in an issue, I'd say that this is a really good solution for those cases where wrapping is okay. It's elegant, speaks to the spirit of the desired effect and doesn't require modifications to the parent. – Crispen Smith Jun 06 '14 at 01:38
1

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

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

Thanks CSS-Tricks!

kslstn
  • 1,145
  • 1
  • 9
  • 25