JMerritt
JMerritt

Reputation: 113

How to handle responsive/fluid images with margins?

I ran into a little hiccup when attempting to apply responsive image techniques. I'm using the "max-width: 100%;" trick to ensure that images widths are constrained by the size of their container.

I ran into a hiccup, however, in cases where an image has an inline padding specified. It seems a padding of X allows the image to be X wider than its container.

Simple example below with inline styles (for simplicity's sake) - the containing div has a border so you can see that the contained image breaks the div width when the window is resized small enough:

<div style="width: 50%; border: 1px solid black;">
    <img src="someimage.png" style="max-width: 100%; padding: 2%;"/>
</div>

Can someone clarify what is going on and perhaps offer a solution? Unfortunately I'm working with a CMS that allows users to specify padding around images.

Upvotes: 1

Views: 227

Answers (1)

fanfavorite
fanfavorite

Reputation: 5199

The problem is that it is setting the width to 100% and then adding the padding. To make the width include the padding, set the box sizing to border-box using these CSS properties:

-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box; 

Upvotes: 2

Related Questions