Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

css: adding a background-image-url on an anchor tag

I'm trying to add social icons on the footer of a webpage via one single sprite image.

I can't get the <a> tag to have a background-image: url. Seems to work fine for other elements like <li> though.

#no-work a {
  width: 50px;
  height: 50px;
  Background-image: url("http://via.placeholder.com/50x50/0ff");
}

#works li {
  width: 50px;
  height: 50px;
  Background-image: url("http://via.placeholder.com/50x50/0ff");
}
// This doesn't work
<ul id="no-work">
  <li>
    <a href=""></a>
  </li>
  <li>
    <a href=""></a>
  </li>
</ul>

// But why does this work???
<ul id="works">
  <li></li>
  <li></li>
</ul>
like image 751
Vincent Tang Avatar asked Mar 07 '23 05:03

Vincent Tang


2 Answers

Anchor tags are inline elements. That means their width and height are defined by their contents. You have blank anchor tags.

The simplest solution is to style the a tags with display: inline-block. This allows your width and height values to work. See the edits to your code:

#works-now a {
  display: inline-block;
  width: 50px;
  height: 50px;
  Background-image: url("http://via.placeholder.com/50x50/0ff");
}

#works li {
  width: 50px;
  height: 50px;
  Background-image: url("http://via.placeholder.com/50x50/0ff");
}
// This works now
<ul id="works-now">
  <li>
    <a href=""></a>
  </li>
  <li>
    <a href=""></a>
  </li>
</ul>

// But why does this work???
<ul id="works">
  <li></li>
  <li></li>
</ul>
like image 184
Hans Avatar answered Mar 27 '23 21:03

Hans


It will work, but you need to put a display:block on your <a> tag.

#no-work a {
  display: block;
  width: 50px;
  height: 50px;
  background-image: url("http://via.placeholder.com/50x50/0ff");
}

#no-work a {
  display: block;
  width: 50px;
  height: 50px;
  background-image: url("http://via.placeholder.com/50x50/0ff");
}

#works li {
  width: 50px;
  height: 50px;
  background-image: url("http://via.placeholder.com/50x50/0ff");
}
<ul id="no-work">
  <li>
    <a href=""></a>
  </li>
  <li>
    <a href=""></a>
  </li>
</ul>

// But why does this work???
<ul id="works">
  <li></li>
  <li></li>
</ul>
like image 26
Daniel Avatar answered Mar 27 '23 21:03

Daniel