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

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

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

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( 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+)
  • 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 and web site design. His expertise is WordPress & Magento as well as many other frameworks. Would you like to work with Nathan? Send him an email on [email protected]

It’s good to share

Join the discussion