1

Just wondering why .border will not wrap around nested divs d1, d2, d3.

The div with id main1 has a 5px solid border that I am trying to wrap around the three nested divs with ids div1, div2, div3. Each of the nested divs have there own 2px solid border. Seems like it should work but maybe something is getting overwritten somewhere.

enter image description here

.border {border: 5px solid RosyBrown;}
.border-thin {border: 2px solid RosyBrown;}
div#main1 {width: 90%;margin: 0 auto 0 auto;}
div#d1 {width: 31%; float: left;}
div#d2 {width: 31%; float: left; margin: 0 0 0 3.5%;}
div#d3 {width: 31%; float: right;}

<div id="main1" class="center border">
   <p>Main</p>
     <div id="d1" class="border-thin">
       <p>d1</p>
     </div>
     <div id="d2" class="border-thin">
       <p>d2</p>
     </div>
     <div id="d3" class="border-thin">
      <p>d3</p>
     </div>
</div>
Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
wallwalker
  • 591
  • 7
  • 14
  • 27
  • You have to clear the float. – Huelfe Oct 14 '16 at 12:05
  • Floated elements are not considered when calculating the height of parent elements. Google for "css clearfix". Remove `

    Main

    ` and you will see your `div#main1`'s height will totally collapse because all its children float, leaving it at a computed height of 0. Also, I highly recommend you never use id selectors in css unless you know exactly **why** you are using them.
    – connexo Oct 14 '16 at 12:06

2 Answers2

3

Since you haven't cleared the floats, as it doesn't take up the view's flow. Give:

overflow: hidden;

to the parent div, or you can use the clearfix.

.border {
  border: 5px solid RosyBrown;
}
.border-thin {
  border: 2px solid RosyBrown;
}
div#main1 {
  width: 90%;
  margin: 0 auto 0 auto;
  overflow: hidden;
}
div#d1 {
  width: 31%;
  float: left;
}
div#d2 {
  width: 31%;
  float: left;
  margin: 0 0 0 3.5%;
}
div#d3 {
  width: 31%;
  float: right;
}
<div id="main1" class="center border">
  <p>Main</p>
  <div id="d1" class="border-thin">
    <p>d1</p>
  </div>
  <div id="d2" class="border-thin">
    <p>d2</p>
  </div>
  <div id="d3" class="border-thin">
    <p>d3</p>
  </div>
</div>

Preview

--

Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
2

That's due to the float elements. By default they are not included in other DIVs' height.

Add overflow: hidden; to #main1. I know that sound strange, but it's working...

Johannes
  • 64,305
  • 18
  • 73
  • 130