stef stef - 4 months ago 12
CSS Question

css: border on an image, not outside it

When you apply a border: 5px solid #000; on an image, the border appears around / outside the image. Is there a way of placing the border "on" the image so that it masks the 5 outer pixels of the image?

Answer

As has been said, wrap the image in a container div. But, the container div must be smaller than the image, and the widths, heights, positions, and thicknesses coordinated.

Like so:

<style>
    #ImgBorder {
        width:      440px;  /*Set to picture  width minus 2 times border thickness.*/
        height:     327px;  /*Set to picture height minus 2 times border thickness.*/
        margin:     0;
        padding:    0;
        border:     5px solid #000;
        overflow:   hidden
    }
    #ImgBorder img {
        width:      450px;  /*Set to picture width.*/
        height:     337px;  /*Set to picture height.*/
        margin:     0;
        padding:    0;
        border:     none;
        position:   relative;
        top:        -5px;   /*Adjust by border thickness.*/
        left:       -5px;   /*Adjust by border thickness.*/
    }
</style>

<div id="ImgBorder">
    <img src="http://bioweb.uwlax.edu/bio203/s2008/kwong_hoi/images/Adorable-Cats-Screensaver.jpg">
</div>

Update: jQuery solution:

You can see it in action at jsFiddle.

<script type="text/javascript">
    $(window).load (jQueryMain);

    function jQueryMain () {
        var BorderWidthPx   = 5;

        //--- Put frame div around marked
        $("img.FrameMe").wrap ('<div class="FrameMe">');

        $("img.FrameMe").each ( function () {
            //--- Adjust dimensions of Frame.
            $(this).parent ()[0].style.width    = ($(this).outerWidth  (true) - 2*BorderWidthPx) + 'px';
            $(this).parent ()[0].style.height   = ($(this).outerHeight (true) - 2*BorderWidthPx) + 'px';

            //--- Set positioning
            $(this).css ( {
                'top': -1*BorderWidthPx + 'px', 'left': -1*BorderWidthPx + 'px', 'position': 'relative'
            } );
        } );
    }
</script>
<style>
    div.FrameMe {
        margin:     0;
        padding:    0;
        border:     5px solid #000;
        overflow:   hidden
    }
    img.FrameMe {
        /* Will set dimensions and positioning with jQuery. */
        margin:     0;
        padding:    0;
        border:     none;
    }
</style>

<img class="FrameMe" src="http://i.stack.imgur.com/aAAeG.jpg">