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:
1 2 3 4 |
<div id="outer"> <div id="inner"> </div> </div> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
#outer { background-color:#999; width:80%; margin:0 auto; height:40px; overflow:visible; } #inner { background-color:#066; height:20px; margin:0 auto; padding:0 40px; width:95%; } |
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)
1 2 3 4 5 6 7 8 9 10 11 12 13 |
#outer { background-color:#999; width:80%; margin:0 auto; height:40px; overflow:visible; } #inner { background-color:#066; height:20px; margin:0 2.5%; padding:0 40px; } |
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!
2 Comments on “Responsive Width Element with Padding – CSS How-to”
Hi Brian,
I’m very interested in your solution, but both CSS seem to be the same to me.
Is there a little mistake?
Thanks
Daniel
Ah, good spot! They were indeed the same. I have changed the code to reflect what it was supposed to be. I also added a JSFiddle to illustrate.