Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested divs producing a scrollbar. Why?

I have 3 nested divs:

<div class="outer">
  <div class="inner"><div class="item"></div></div>
</div>

The .inner div is position absolute and they each have 1px border:

.outer{
  width:50%;
  height:100px;
  border: 1px solid red;
  position:relative;
  overflow-x:hidden;
  box-sizing:border-box;
}
.inner{
  border:1px solid blue;
  height:100%;
  position: absolute;
  box-sizing: border-box;
}
.item{
  width:100px;
  height:100%;
  background-color:yellow;
  display: inline-block;
  border:1px solid green;
  box-sizing:border-box;
}

This arrangement results in a scrollbar on the .outer div.

Here's a codepen

Why is this and what do I need to change to stop it happening?

If the width of the border of the .inner div is increased to 3px then the scrollbar goes away. Again, why is this happening?

like image 758
Will Jenkins Avatar asked Oct 07 '15 14:10

Will Jenkins


1 Answers

This is happening because your .item element is set to display as an inline-block. This means it's affected by things like line-height and vertical-align.

The default vertical alignment on inline-block elements is baseline. This means they're set to appear at the base line of any text that may be entered alongside it. I'm not 100% sure but I think there may be an issue here where box-sizing is ignored when making this calculation, and the base line ends up being 2 pixels below where it should be (due to the cumulative 2 pixels of border applied to the top and bottom of the element).

If you want that element to remain being displayed this way, a quick fix is to set its vertical-align to top:

.item {
    ...
    vertical-align: top;
}

Codepen demo.

like image 111
James Donnelly Avatar answered Sep 30 '22 21:09

James Donnelly