jDogg jDogg - 28 days ago 10
CSS Question

Why does increasing height of div move div down?

The code

I'm making a grid of names out of divs, and to start off I made some fixed width boxes. Here's the relevant HTML:

<div id="names">
<div class="row">
<div class="item">hi</div>
<div class="item"></div>
</div>
</div>


relevant CSS:

#names {
background-color: rgb(191, 191, 191);
width:80%;
margin-left: auto;
margin-right: auto;
border: 1px solid green;
}
.row {
text-align: center;
border: 1px solid red;
background-color: rgba(255,0,0,0.2);
height:80px;
text-align: center;
}
.item{
display: inline-block;
text-align: center;
background-color: rgba(0,0,255,0.2);
width:50px;
height: 100%;
margin-left: 50px;
margin-right: 50px;
border: 1px solid blue;
}


For whatever reason, when there is text or an element in the divs, they are placed lower than if there is nothing inside them. In addition, the greater the
height
attribute is in
.item
, the farther down the divs are. This can be fixed with a negative
margin-top
, but it is likely to lead to problems in the future, and regardless I'd like to know the cause of this behavior.

Why is this happening? Why is it only happening with content inside the divs? Why does the height attribute have anything to do with it? Any info would be greatly appreciated!

Answer

The initial value of vertical-align is baseline.

From http://www.w3.org/TR/2008/REC-CSS2-20080411/visudet.html#line-height:

vertical-align: baseline — align the baseline of the box with the baseline of the parent box. If the box doesn't have a baseline, align the bottom of the box with the parent's baseline.

Adding vertical-align: top; to .item should solve your problem. Also make sure to use box-sizing: border-box; to prevent the items to have a greater height than it's parent. http://codepen.io/anon/pen/eBNgWe

Comments