WordPress / Web Development Tutorials
(Best WordPress Tutorials)

CSSHTMLJavaScriptjQueryMySQLPHPSilvaTechnologiesWooCommerceWordpress
Silva Web Designs - Blog

Replace an image in an using CSS

Today we are going to show you a nice little feature using CSS box-sizing as an image replacement technique.

I stumbled across this when I was asked to replace an on of the sites we built with another image hosted elsewhere. Sounds easy right? But the catch was I would not be able to replace the markup as it was already deployed to production, but could inject CSS or JS through our CMS. For whichever technology I chose, it would be inserted on all site pages. I only needed on one specific page, and the attributes of parent containers were non-specific to the desired page.

Okay so let’s say we have the following HTML:-


<head>
  <title>Your Page Title</title>
</head>
<body>
  <!-- .header would be across site on other pages with different children, so no background image adding -->
  <div class="header">
    <img decoding="async" class="banner" src="//exampledomain.com/banner.png">
  </div>
</body>

This is simple to do with JavaScript, but I wanted to see if there was another, more simpler, way. After a few iterations in Chrome Dev Tools, I thought to use the box-sizing property to keep dimensions strict, add the new image as a background image, and just push the inline image out of the way with padding and see what happened.


/* All in one selector */
.banner {
  display: block;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
  background: url(http://exampledomain.com/newbanner.png) no-repeat;
  width: 180px; /* Width of new image */
  height: 236px; /* Height of new image */
  padding-left: 180px; /* Equal to width of new image */
}

It worked perfectly and here are some reasons why:-

  • It works on just about any element, even empty ones like or

  • Browser support is excellent (Chrome, Firefox, Opera, Safari, IE8+) http://caniuse.com/#feat=css3-boxsizing
  • Refrains from using SEO unfriendly display: none or other properties

That last point seemed important, as it works really well for text replacement too without any adjustment.

 

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

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