WordPress / Web Development Tutorials
(Best WordPress Tutorials)

CSSHTMLJavaScriptjQueryMySQLPHPSilvaTechnologiesWooCommerceWordpress
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:

HTML


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

</div>

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:

CSS


.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 - How to calculate CSS letter-spacing vs. “tracking” in typography? Photoshop/Illustrator to CSS

CSS / 18th March 2025

How to calculate CSS letter-spacing vs. “tracking” in typography? Photoshop/Illustrator to CSS

Read More Related - How To Create A Modern Scroll Down Animation Icon With CSS

CSS / 14th March 2025

How To Create A Modern Scroll Down Animation Icon With CSS

Read More