Helping you build a better website
(and other interesting web stuff)

CSSHTMLJavaScriptjQueryMSSQLMySQLPHPSilvaTechnologiesWordpress
Silva Web Designs - Blog

Replacing an image with a different using CSS

Have you ever needed to replace an image or even a logo for a specific page without using jQuery or JavaScript? Well you can with just pure CSS using box-sizing.

I was working on a website and my client had a specific request, this was to replace their logo with a different (similar logo) for a specific page only. The website was built using WordPress therefore the logo was always set in place using the header.php file like you would find in any CMS.

Replacing an image with a different using CSS is as simple as:-

HTML


<div class="logo logo-image">
	
    <h3>
        <a href="http://web-tricks.co.uk/demo">
	    <img src="https://web-tricks.co.uk/images/03_logo-dark.png" alt="Web-Tricks Logo" />
        </a>
    </h3>

</div>

Although this is simple to do with JavaScript or jQuery, I wanted to see if there a different method. The end result we came up with was using the box-sizing property to keep dimensions strict, add the new image as a background image, and then just pushing the inline image out of the way with padding as follows:-

CSS


.logo-image img {
    display: block;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
    background: url(https://web-tricks.co.uk/images/03_logo-dark.png) no-repeat;
    width: 173px; /* Width of the new image */
    height: 60px; /* Height of the new image */
    padding-left: 173px; /* Equal to the width of the new image */
}

And guess what, it works perfectly!

The benefits of this method is that:

  • It works on just about any element, even empty ones like images or the horizontal rule
  • It works across all browsers! (Chrome, Firefox, Opera, Safari, IE8+)
  • Doesn’t go against your SEO, where as display: none or other properties would.

Give it a try and let us know if it helped you out.

 

It’s good to share

One thought on “Replacing an image with a different using CSS

Join the discussion