WordPress / Web Development Tutorials
(Best WordPress Tutorials)

Silva Web Designs - Blog

Replacing an image with a different using CSS

Have you ever needed to replace an image like a logo for a specific page without using jQuery or JavaScript? Well, this can be done 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 as you would find in any CMS.

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


<div class="logo logo-image">
        <a href="/demo">
	    <img decoding="async" src="/images/03_logo-dark.png" alt="Silva Web Designs Logo" />


Although this is simple to do with JavaScript or jQuery, I wanted to see if there was 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:


.logo-image img {
    display: block;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
    background: url(/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.


Nathan da Silva - Profile

Posted by: Nathan da Silva

Nathan is the Founder of Silva Web Designs. He is passionate about web development, website design and basically anything digital-related. His main expertise is with WordPress and various other CMS frameworks. If you need responsive design, SEO, speed optimisation or anything else in the world of digital, you can contact Silva Web Designs here; [email protected]

It’s good to share

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

Join the discussion

Related Posts

Related - Best Practices To Maximise The Effective Use Of Photos In HTML

HTML / 16th February 2022

Best Practices To Maximise The Effective Use Of Photos In HTML

Read More Related - How to Limit Text Length to X Lines Using CSS

CSS / 15th February 2022

How to Limit Text Length to X Lines Using CSS

Read More