1

I'm trying to center one div responsively by wrapping it between two divs - the centerdiv and the sidedivs.

The code:

.overmiddlediv {
  width: 100%;
  height: 150px;
  background-color: blue;
  float: left;
}
.sidedivs {
  width: 25%;
  float: left;
  padding-left: 50px;
  background-color: red;
}
.centerdiv {
  width: 50%;
  float: left;
  background-color: white
}
<div class="overmiddlediv">
  <div class="sidedivs">
    <p>Left side</p>
  </div>
  <div class="centerdiv">
    <p>This is the middle and is 50%</p>
  </div>
  <div class="sidedivs">
    <p>Right side</p>
  </div>
</div>

The JSFiddle at this link shows the output and it's incorrect, as the right side is on the left when it should be on the right of the white piece and should also be 25%.

I've played around with removing the float:left on the .sidedivs and tried an absolute position, but no success. What's odd is that I've used this same structure of code for a footer and it worked exactly like it should - separating each piece by the required 25%-50%-25%, but on this it doesn't and I'm not sure what I'm missing.

See this JSFiddle where all the left elements and p tags have been removed.

kukkuz
  • 41,512
  • 6
  • 59
  • 95
wpquestionz
  • 149
  • 8
  • you have a class that has float:left attached to both side divs so they will both go to the left – Keith Sep 30 '16 at 17:03
  • remove the `padding` or use `* { box-sizing: border-box; }` or you should adjust the 25%-50%-25% width distribution using `calc` to prevent the wrapping. – kukkuz Sep 30 '16 at 17:05
  • @Keith Thanks, but even if I remove those, as I put in my post, it still wraps it incorrectly. See this fiddle for an example - https://jsfiddle.net/pe8smexz/1/. – wpquestionz Sep 30 '16 at 17:07

3 Answers3

2

Add this to the CSS so that your percentage values aren't influenced/altered by paddings and margins:

html, body {
  margin: 0;
}
* {
  box-sizing: border-box;
}

https://jsfiddle.net/hkq7ttvj/1/

Johannes
  • 64,305
  • 18
  • 73
  • 130
  • Worked; I didn't realize that the default body has a set margin, but that's very helpful to know. I'll have to look at what border-box does. – wpquestionz Sep 30 '16 at 17:14
  • 1
    @wpquestionz read [this](http://stackoverflow.com/questions/39129811/add-border-to-div-increase-div-width/39130170#39130170) to know more about `border-box`. – kukkuz Sep 30 '16 at 17:19
2

You must set box-sizing:border-box: https://jsfiddle.net/v9f1qbng/1/ otherwise the width is added to padding size.

Stefano Balzarotti
  • 1,760
  • 1
  • 18
  • 35
1

Remove the padding from the sidedivs or use:

 * { 
   box-sizing: border-box; 
 } 

Revised fiddle

Read this answer to know more about border-box.

Or you should adjust the 25%-50%-25% width distribution using calc to prevent the wrapping.

Community
  • 1
  • 1
kukkuz
  • 41,512
  • 6
  • 59
  • 95