Grow your CSS skills. Land your dream job.

How a 1px border affects percentage widths

  • # September 10, 2012 at 12:25 am

    In the following example, there are 4 responsive images set up 4 in a row with 1% margins and 1% padding, which all works and scales just fine, but when I add a 1px border to the images, it breaks. How do you adjust the %’s to account for the space a 1px border takes up? I commented out the border for now, but was wondering if there is a formula for this, or a different way that it should be marked up (like in a container or something)? Thanks!

    http://codepen.io/msguerra74/pen/GEvlu

    # September 10, 2012 at 12:45 am

    The solution is to use box-sizing: border-box; but this will also alter the behavior of the padding, so you will have to adjust the width to account for that. Also, you are using JavaScript comments in CSS?

    # September 10, 2012 at 12:46 am

    See here for more info: http://css-tricks.com/box-sizing/

    # September 10, 2012 at 12:51 am

    Haha, oops, I was messing with js earlier and commented the CSS wrong! Funny that it worked though. Anyway, I’ll take a look at the link you posted. Thanks for your feedback!

    # September 10, 2012 at 2:10 pm

    Hi Msguerra,

    Add this css in img class.
    It will work.

    box-shadow:0 0 1px 0 #000;

    # September 10, 2012 at 7:17 pm

    @sachinn That is another option, although you probably want to use the spread value rather than the blur (e.g. box-shadow: 0 0 0 1px #000;).

    The reason I suggested using box-sizing instead of box-shadow is that it has slightly better browser support (IE8 for instance).

    # September 10, 2012 at 9:41 pm

    you could also just apply the float, padding, and margin to the anchors and the borders to the images

    # September 10, 2012 at 10:17 pm

    Haha, yeah, do what @wolfcry911 suggested. Man, I way over-thought that!

    # September 11, 2012 at 3:12 am

    You could also use calc().

    # September 11, 2012 at 9:29 pm

    @joshuanhibbert, box-sizing worked perfectly and seems to have pretty good browser support as long as you add the appropriate -prefixes- where necessary. I tried what @wolfcry911 suggested too, but when I add padding to the img tag, it makes the right margin vanish. I tried the padding on the anchor, but it didn’t pad the image inside the border, which is what I was looking for. Anyway, take a look if you want and you’ll see what I mean if you uncomment the padding.

    This is adding the properties to the a and img elements:
    http://codepen.io/msguerra74/pen/Hzdpw

    This is using box-sizing:
    http://codepen.io/msguerra74/pen/GEvlu

    Thanks again for the suggestions!

Viewing 10 posts - 1 through 10 (of 10 total)

You must be logged in to reply to this topic.

*May or may not contain any actual "CSS" or "Tricks".