How to insert image in after and before property in css also handling it's sizing

43 Views Asked by At

i don't know why my code is not working btw i want to add image in content of before property of css and i already done this but i don't know how i give size what i want because that image in it's actual size right now



li::after{

    content:" ";

    width: 70px;

    height: 70px;

    top: 10px;

    background-image: url("https://i.pinimg.com/originals/9f/16/32/9f163259165a9031b62fbd8c38746645.jpg?hl=en_US");

    background-repeat:no-repeat ;

    background-size:70px 70px;

    border-radius:35px;

    position: absolute;

    border-top:2px solid #222;

    background:#222;

    justify-content:center;

}


i want to short this problem of sizing of image in content of before property

2

There are 2 best solutions below

3
AngYC On

If what you need is to ensure the image always fit inside the box (70x70px), you can use background-size: cover CSS value to ensure the image always cover the full size (but with some parts of it cropped). In addition, if you want the image to always be center-aligned, you can use background-position: center CSS value instead of justify-content (which is used for Flex instead)

li::after {
  content: ' ';
  width: 70px;
  height: 70px;
  top: 10px;
  background-image: url('https://i.pinimg.com/originals/9f/16/32/9f163259165a9031b62fbd8c38746645.jpg?hl=en_US');
  background-repeat: no-repeat;
  background-size: cover;
  background-position: center;
  border-radius: 35px;
  position: absolute;
  border-top: 2px solid #222;
}

li:hover::after {
  background-image: url('https://placekitten.com/200/200');
}
<ul>
  <li>Test</li>
</ul>

0
A Haworth On

Your code is fine except you have put a background: #222 after setting the background-image. This overrides the background-image.

If you want to put a background-color as well then state this explitly (or put the background: #222 before the background-image setting).

<style>
  li::after {
    content: " ";
    width: 70px;
    height: 70px;
    top: 10px;
    background-image: url("https://i.pinimg.com/originals/9f/16/32/9f163259165a9031b62fbd8c38746645.jpg?hl=en_US");
    background-repeat: no-repeat;
    background-size: 70px 70px;
    border-radius: 35px;
    position: absolute;
    border-top: 2px solid #222;
    background-color: #222;
    justify-content: center;
  }
</style>
<ul>
  <li>
  </li>
</ul>