How to keep outer div not be pushed out by inside div's padding/margin?
Asked Answered
R

3

5

Here's the jsfiddle example

Here's the html:

<div class="header">header</div>
    <div class="wrapper">
        <div class="left"><div class="content"></div></div>
        <div class="right">right</div>
    </div>

Here's the css:

.left{
position:absolute;
width:30%;
background:red;
left:0;
height:100%;
display:block;
padding:5px;
}
 .right{
overflow:hidden;
background:green;
position:absolute;
right:0;
width:70%;
height:100%;
}

html, body{
min-height:100%;
height:100%;
padding:0px;
margin:0px;
position:relative;
}

body {position:relative;}

.wrapper {
position:relative;
height:100%;
}

.header{
width:100%;
height:100px;
background:yellow;
display:none;
}

.left .content {
background:blue;
height:inherit;
width:100%;
}

You can see the red div being pushed out by the blue div. How can I prevent that? All the width and height are based on %. The only way I know is to give the red div a fixed width. I s there any other way that it can be done with %?

Rattigan answered 12/3, 2013 at 9:29 Comment(0)
S
6

You want to use box-sizing, see this updated example: http://jsfiddle.net/Lca5c/1/

Your CSS will look like:

.left{
    position:absolute;
    width:30%;
    background:red;
    left:0;
    height:100%;
    display:block;
    padding:5px;
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
}

The reason it's been pushed out is due to the padding you've added to to div. Make sure you check out the browser compatibility (here) to see if it matches your requirements.

Stylist answered 12/3, 2013 at 9:33 Comment(0)
J
5

I know that is a old post. The best solution is to add

-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
-ms-box-sizing: border-box;
-o-box-sizing: border-box;
box-sizing: border-box;

on your element what is in your outher box.

You can do that with div, textarea, input, select or any other element in HTML.

Joyner answered 14/5, 2015 at 12:30 Comment(1)
I kinda figured that out with the help in here too. Thanks anyway!Rattigan
S
1

The simplest method would be to remove the padding from .left and add the padding to .content whilst also removing the width from .content so it defaults to auto width.

Doing that will result in the correct behaviour that you want and won't rely on the CSS3 box-sizing method.

Additionally you don't have to tell a DIV to display:block as that is its default display property.

.left{
    position:absolute;
    width:30%;
    background:red;
    left:0;
    height:100%;
}

.left .content {
    background:blue;
    height:inherit;
    padding:5px;
}
Shimmery answered 12/3, 2013 at 9:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.