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 decoding="async" 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.
Hello