Mobile Friendly Padding

Fit it in the box!

Responsive design is everything these days. We’ve gotta do it. How many times though have you scaled down the page and find it frustrating to work with left-right padding or margins to keep the content off of the edge of the page. If you add padding to your element, you have to change the width, and keeping track of all of that can be a hassle.

I know that we can use CSS box-sizing, but it isn’t compatible with IE7 or earlier (not that I de). One thing that I’ve been doing a lot recently should definitely account for earlier browsers as well as new ones, and it doesn’t take much. I find the quickest way to deal with this situation is to add a

<div class="padding">

inside the element that you want to change. This should wrap around all the element contents and be closed just before the element itself is closed. After accomplishing this, you can style your padding like so:

.my-div > .padding {
  width: auto;
  padding: 10px 20px;
}

You do not need to set your width to auto, but I put that there to remind you of the importance of not setting a width on padding. The width should automatically be set to 100% minus the padding you set, so you want to leave it as auto or inherit.

This allows for you to set your div (.my-div) at whatever width you want and set a max-width of 100% on it, and your padding will not cause your div exceed the width of the screen on smaller devices.

Leave a Reply

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

css.php