Nesh
Nesh

Reputation: 2541

Adding an extra padding to a div causing other divs to move down - CSS?

I created a fiddle which is working fine but whenever I am trying to add an extra left padding to lef-col, the other two divs move downside.

What I am expecting is that padding applies to the inner content and the outer boundary of div, but in this case it looks like it is adding to the div calculation. Let me know what I understand incorrectly for passing.

PS - I fixed by applying box-sizing: border-box to left-col . I am looking for e.xplanation for this cause than solution(though alternate solutions are welcome too !!)

Code -

HTML -

<div class="container">
        <div class="left-col">
            <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dignissimos illum perferendis corporis, nemo dolorem, mollitia at sequi quis corrupti. Fugit eaque dolores inventore, aliquam quisquam, saepe officiis eos quia at!</p>
        </div>
        <div class="mid-col">
            <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dignissimos illum perferendis corporis, nemo dolorem, mollitia at sequi quis corrupti. Fugit eaque dolores inventore, aliquam quisquam, saepe officiis eos quia at!</p>
        </div>
        <div class="right-col">
            <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dignissimos illum perferendis corporis, nemo dolorem, mollitia at sequi quis corrupti. Fugit eaque dolores inventore, aliquam quisquam, saepe officiis eos quia at!</p>
        </div>
    </div>

CSS -

*, html {
    margin: 0;
    padding: 0;
}

body {}

.container {
    padding: 20px;
    overflow: hidden;
}

.left-col, .mid-col, .right-col {
    width: 33.3%;
    float: left;
}

.left-col {
    background: lightpink;
}

.mid-col {
    background: lightgreen;
}

.right-col {
    background: lightblue;
}

Fiddle - https://jsfiddle.net/km2brd8m/

Upvotes: 2

Views: 932

Answers (3)

Asons
Asons

Reputation: 87191

If you add box-sizing: border-box to left-col it will work, and the reason is that when using box-sizing: border-box the padding is included in the set width.

Updated fiddle


You can also subtract the padding from the width using CSS Calc

.left-col {
    width: calc(33.3% - 20px);
    background: lightpink;
    padding-left: 20px;
}

Updated fiddle

Upvotes: 5

Alex
Alex

Reputation: 4774

The padding increases the space used by the element, just like margin. border-box makes it use space from the element itself, instead of increasing its size.

You can read more about it here.

Upvotes: 1

Jonathan Bartlett
Jonathan Bartlett

Reputation: 512

Add the box-sizing: border-box; property to the three columns. This will include the padding it the overall dimensions instead of outside the original dimensions as it is currently doing.

Upvotes: 2

Related Questions