Isengardium
Isengardium

Reputation: 115

Padding inside DIV

Why does adding some padding affects elements outside the DIV box? Padding isn't supposed to create some space between the border of the DIV and contents inside it? How can you create this space without affecting elements outside the DIv box?

Upvotes: 1

Views: 6727

Answers (3)

Danield
Danield

Reputation: 125641

How can you create this space without affecting elements outside the DIv box?

Use box-sizing: border-box

From MDN:

border-box The width and height properties include the padding and border, but not the margin.

The reason that this property must be set is because by default the value for box-sizing is content-box. Again from MDN:

content-box This is the default style as specified by the CSS standard. The width and height properties are measured including only the content, but not the padding, border or margin.

Upvotes: 10

David Wilkinson
David Wilkinson

Reputation: 5118

Try looking into the box-sizing property...

https://css-tricks.com/box-sizing/

Today, the current versions of all browsers use the original "width or height + padding + border = actual width or height" box model. With box-sizing: border-box;, we can change the box model to what was once the "quirky" way, where an element's specified width and height aren't affected by padding or borders. This has proven so useful in responsive design that it's found its way into reset styles.

The value you're after is border-box:

.class {
    box-sizing: border-box;
}

Upvotes: 1

Quentin
Quentin

Reputation: 944442

Assuming you have specified a content height or width, then padding will be placed around that. That moves the border outwards. That moves the margin outwards. That pushes nearby elements away.

You can change it by reducing the height and/or width to compensate or by using the box-sizing property to make height and width determine the distance between the outside edges of the border instead of the outside edges of the content.

Upvotes: 1

Related Questions