This is a quick-tip type post, nothing major but a simple and effective tip for getting responsive borders on responsive images in your responsive designs.
As we know all too well, we can’t specify borders as percentages. This is a major annoyance if you’re working (or attempting to work) large borders into a responsive design. It may not be all that difficult with images, it turns out.
Instead of applying something like this:
img{
max-width:100%;
border:5px solid red;
}
Simply use:
img{
max-width:98%;
padding:1%; /* A percentage that, when doubled and added to the above, makes 100%. */
background:red; /* Color of the faux border. */
}
Demo
I made a jsFiddle and here is its output.
Now this does seem ridiculously obvious but a quick bit of Googling (other search engines are available) yielded nothing similar. Apologies is someone’s beaten me to this and I’m retreading old ground.
By Harry Roberts on Sunday, July 31st, 2011 in Web Development. Tags: Images, Responsive web design | 9 Comments »
+
Steve Rydz said on 31 July, 2011 at 7:16 pm
That’s a good solution Harry and one I will no doubt use in future projects.
I’m still trying to come up with a solution for responsive borders when for example you have a white background, 9px padding and a 1px grey border.
Adam said on 1 August, 2011 at 12:14 am
@Steve Rydz — you could do an outline as the “second border”–outlines stay outside of the box and do not affect the layout.
Christian Krammer said on 1 August, 2011 at 6:00 am
Thanks for the tip, never thought about that. Will maybe try it out at my current project.
Jamàl said on 1 August, 2011 at 9:15 am
Unfortunately, this solution will fail if the image is semitransparent as the background color behind the image will be leaked in this case.
Ankur said on 1 August, 2011 at 10:22 am
sweet, thanks for the tip!
Steve Rydz said on 1 August, 2011 at 1:06 pm
@adam Thanks for the tip. That’s certainly an option to consider.
@jamal All solutions will have flaws but for regular images such as photos this is a great solution.
Nicolas Gallagher said on 1 August, 2011 at 3:08 pm
Depending on the project/effect, some other options (which make fixed-pixel borders, and borders + background possible) are to use border-box or a pseudo-element.
Nico said on 6 August, 2011 at 7:29 pm
Just use:
img{
max-width:100%;
border:5px solid red;
box-sizing:border-box;
}
Jonathan Nicol said on 10 September, 2011 at 3:58 am
@Nico – pure brilliance! Thanks for sharing.