Responsive Width Element with Padding – CSS How-to

Padding Extends Beyond Parent Element

Have you ever had an element in your responsive website design which needed some padding, but you couldn’t add it because it broke the design? There’s a solution to that problem.

Normally, the element in question will just add padding to the outside of itself, often expanding well beyond the space it is supposed to take up. But there is a way around that.

Consider the following situation. We want the inner div to have 95% of the width of its parent, and still have 40px of padding on each side. So we try the following:

Padding Extends Beyond Parent Element

As you can see, the inner div expands beyond its parent due to the padding. It’s also supposed to be centered, but clearly that isn’t happening. So what are we to do? Simple!

1. Remove the width. We won’t be needing an explicit width.
2. Set the right and left margins to cover the width.

Our new CSS will look like this: (Fiddle)

Padding Fits Well

In this illustration you can see that the whole thing is the appropriate width and also the padding is in effect. With this method, margins will shrink or grow the entire size of the element, while padding will come from the inside without adjusting the overall width. Try it out!

One thing to keep in mind, this will only work for BLOCK LEVEL elements. If you are dealing with links or spans or any other inline elements, you will need to specify display:block; in order for this to work. It is taking advantage of the fact that block level elements like to be full width.

Here is a JSFiddle I created so you can see it in action!

About Brian Johnson

Brian Johnson is a website developer and designer living in Minneapolis, Minnesota with a passion for code and WordPress. He spends his days building WordPress websites for small businesses, developing new code with the online community, and living life.

2 Comments on “Responsive Width Element with Padding – CSS How-to”

  1. Hi Brian,
    I’m very interested in your solution, but both CSS seem to be the same to me.
    Is there a little mistake?

Leave a Reply

Your email address will not be published. Required fields are marked *