How to remove a border of background-image

The img tag requires a src attribute. Load a transparent image as the source, and the border will vanish.

body
{
  background-color: grey;
border: none;
}
.footer-red-bar
{
  width: 100%;
  height: 180px;
  margin: 0 auto;
  margin-top: 2em;
}

.footer-red-bar img
{
  width: 100%;
  height: 180px;
  object-fit: cover;
  object-position: top;
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
}
<div class="footer-red-bar">
  <img style="background-image: url(https://www.w3schools.com/css/trolltunga.jpg)" src="http://antonandirene.com/build/images/about/snow-small.png" />
</div>

Use the src="" attribute instead of background-image

That's the usual border of the Broken-Image asset that you get when you don't provide a valid src="" attribute and the image cannot be found.

A BAD solution is to use a 1x1 transparent pixel - or equally a base64 representation of the same:

data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7

than it would look like:

body{
  background-color: grey;
}

.footer-red-bar{
  width: 100%;
  height: 180px;
  margin: 0 auto;
  margin-top: 2em;
}

.footer-red-bar img{
  width: 100%;
  height: 180px;
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
}
<div class="footer-red-bar">
  <img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" 
       style="background-image: url(https://www.w3schools.com/css/trolltunga.jpg)"/>
</div>

But that's not the way to do it.

img elements not only need a valid image source trough the src="" attribute, but also the alt="" attribute - which explains to Search Engine Bots and screen readers the subject of the image. A transparent pixel is clearly not something worth an Alternative attribute.

Therefore

  1. use your <img src="image.jpg" alt="Nice green nature">

  2. or use <div style="background-image='url(image.jpg)'"></div>

If you use <img> but need a cover translation like it's done by background-size: cover;...

use object-fit: cover;

Opera Mini has it, so you can expect soon IE/Edge will (eventually) implement that feature too.

object-fit/object-position shipped in Microsoft Edge included in Windows Insider Preview build 16215.

Or use Google and do a research for neat fallbacks.


Using the content css property worked for me:

css

img.my-img {
  content: url(https://www.w3schools.com/css/trolltunga.jpg);
}

html

<div>
  <img class="my-img"/>
</div>

JSFiddle

Tags:

Html

Css