jDogg jDogg - 1 year ago 71
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>

relevant CSS:

#names {
background-color: rgb(191, 191, 191);
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);
text-align: center;
display: inline-block;
text-align: center;
background-color: rgba(0,0,255,0.2);
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
attribute is in
, the farther down the divs are. This can be fixed with a negative
, 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 Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download