Search code examples
htmlcssbackground-image

Define image in CSS, not in HTML


I'm having an issue, and I'm not actually sure what is going wrong.

I have an HTML page, and my images are currently linked in as such.

<span class="tribar" onclick="openNav()"><img src="url_here"></span>

I was trying to eliminate all image urls from the HTML source code, and have them in the css. This is what I have tried.

<span class="tribar" onclick="openNav()"></span> // HTML

.tribar {
display: inline-block;
background-image: url("image_url") no-repeat top left;
width: 220px;
height: 220px;
}

But my HTML span is coming up blank, and I can't seem to figure it out.

This should be a simple mistake.


Solution

  • I'd recommend doing it with a <button>:

    function opennav() {
      alert("Hello!");
    }
    .nav-button {
      border: none;
      background: none;
      font-size: 0; /*hide alt text*/
    }
    
    .nav-button:before {
      display: inline-block;
      content: url(http://placekitten.com/220/220);
      width: 220px;
      height: 220px;
      cursor: pointer;
    }
    <button class="nav-button" onclick="opennav()">Alt text for screen readers</button>

    See also on CodePen.