htmlcsscss-floatbox-sizing

Right Div Incorrectly Aligns Left 25% of Page


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.


Solution

  • 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/