Alegro
Alegro

Reputation: 7956

Why the two divs are not aligned?

<div id="container">
  <div id="top"></div>
  <div id="left"></div>
  <div id="right"></div>
  <div id="clear"></div>
</div>
#container{
  width:200px;
  margin-left:auto;
  margin-right:auto;
  margin-top:50px;   
}

#top{
  width:200px;
  height:20px;
  border:medium ridge #FFF;
}
#left{
  float:left;
  width:50px;
  height:20px;
  border:medium ridge #FFF;
}
#right{
  float:right;
  width:40px;
  height:20px;
  border:medium ridge #FFF;
}
#clear{
  clear:both;  
}

Why the #right and #top are not right aligned?

Upvotes: 1

Views: 92

Answers (3)

pgreen2
pgreen2

Reputation: 3651

The problem is how the width is calculated for the box model. All elements on the screen have 4 components (inner to outer): content, padding, border, margin. By default, the width includes only the content. By adding the borders, top becomes larger than 200 pixels. Using the developer tools in chrome, it was rendering as 206px.

There are two possible solutions, one is fudge the widths, or two modify the box model. The first will work, but it is difficult to maintain. Any small change can mess up the alignment.

A better solution is to use box-sizing: border-box. By adding that CSS style, the width attribute will include content, padding, and border. So, originally padding and border wrap around the outside, but with border-box, the encroach on the inside.

Upvotes: 1

Kevin Bowersox
Kevin Bowersox

Reputation: 94429

Its because the top element is actually overflowing the bounds of the container, while the floated element right is being restricted to it. The top element is overflowing the container because the border is not included in the width. So top is actually occupying 204px.

Problem Illustrated via Example: http://jsfiddle.net/KhJ6e/2/

To fix, adjust top to account for the 2px border on each side. (subtract 4 from width of container) or specify width as auto depending on your intentions.

#top{
    width:196px;
    height:20px;
    border:medium ridge #FFF;
}

Example: http://jsfiddle.net/KhJ6e/1/

Upvotes: 3

Timbadu
Timbadu

Reputation: 1551

The top is wider than it's parent container

#top{
  width:auto;
}

Upvotes: 2

Related Questions