Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add padding without changing overall width

How can I add padding to an element without adding on top of the predefined width?

It's good to define the width of a column to make a clean grid for the layout; but also wants to add padding to the contents inside the column. Any way to specify that?

like image 246
user2119834 Avatar asked Mar 13 '13 10:03

user2119834


People also ask

How do you change padding without increasing width?

To avoid the width or height getting increased or decreased when using CSS properties like margin , padding , etc, we can use the CSS property called box-sizing and set its value to border-box on the element in CSS.

Does padding affect width?

Normally, when an element's size is set, the width and height properties determine the width and height of the element's content box. Any padding added to the element will increase the total computed width and/or height of the element—this is how the default box model works in regards to sizing the element.

Does width 100% include padding?

The width and height properties include the content, but does not include the padding, border, or margin.

Does padding add to the width of an element?

Padding and Element Width The content area is the portion inside the padding, border, and margin of an element (the box model). So, if an element has a specified width, the padding added to that element will be added to the total width of the element.


3 Answers

element { 
    -webkit-box-sizing: border-box; /* Safari/Chrome, other WebKit */
    -moz-box-sizing: border-box;    /* Firefox, other Gecko */
    box-sizing: border-box;         /* Opera/IE 8+ */
}
like image 120
Linus Caldwell Avatar answered Oct 17 '22 22:10

Linus Caldwell


Use box-sizing, it makes padding inclusive: https://developer.mozilla.org/en-US/docs/CSS/box-sizing

Example:

div {
    box-sizing:border-box;
    -moz-box-sizing:border-box; /* Firefox */
    -webkit-box-sizing:border-box; /* Safari */
}

It's worth noting that this won't work on IE7.

For IE8, please see the top answer to this Q: box-sizing: border-box => for IE8?

like image 27
Kyuuji Avatar answered Oct 17 '22 20:10

Kyuuji


Everytime you add padding to block element, the width of this element changes. This problem has many solutions. I usually set margin to first child element and set width: 100% for this element.

For example, we have:

<div id="main">
    <div id="child">
        This is content with margin
    </div>
</div>

CSS style for these elements:

#main {
    border: solid 1px red;
    float: left;
    width: 5em;
}

#child {
    border: solid 1px blue;
    float: left;
    width: 100%;
    margin: 0.5em;
}

This is a solution for any browser

like image 3
AlexN Avatar answered Oct 17 '22 22:10

AlexN