Moliere
Moliere

Reputation: 109

How to add background-image with pseudo before

I'm trying to use one image for a list and each li will display different background position, but I can't even get the image to display.

#info li a:before {
background-image: url(img/about/Capture.png) no-repeat;
}

#info li:nth-child(1){
background-size:auto ;
background-position: 0% -6.9%;
}

#info li:nth-child(2){
background-size:auto ;
background-position: 0% 37%;
}

#info li:nth-child(3){
background-size:auto ;
background-position: 0% 73.4%;
}

#info li:nth-child(4){
background-size:auto ;
background-position: 0% 111%;
}

----EDIT---- i just realized i dont actually need any pseudo :P lol i can just do it like that :

#info li{
background: url("img/about/Capture.png") no-repeat ;
background-size:auto ;
}

#info li:nth-child(1){
background-position: 0 -6.9%;
}

#info li:nth-child(2){
background-position: 0 37%;
}

#info li:nth-child(3){
background-position: 0 73.4%;
}

#info li:nth-child(4){
background-position: 0 111%;
}

Upvotes: 0

Views: 8181

Answers (1)

Asons
Asons

Reputation: 87191

Your syntax is wrong, it should look like this.

#info li a:before {
    content: "";
    background: url(img/about/Capture.png) no-repeat;
}

On pseudo element you need to set the content: "" attribute for them to work.

You can't set no-repeat when using background-image:, you need background:.

You might also need width/height to make image visible.

Edit 1, on your comment: Here is 2 samples how you can do.

a.link1:before {
  content: url(http://placehold.it/40x40);
}

a.link2 {
  position: relative;
}

a.link2:before {
  content: "";
  background: url(http://placehold.it/100x40) no-repeat;
  position: absolute;
  height: 100%;
  width: 100%;
  z-index: -1
}
<a class="link1" href="#">This is a link 1</a><br><br>
<a class="link2" href="#">This is a link 2</a>

Edit 2, on your post edit: Yes, of course you can set a background image on your li element.

Upvotes: 1

Related Questions