Search code examples
csshtmlliststylesheet

list style image not working by external style sheet


I write this below Html code:

<!DOCTYPE html>
<html>
<head>
<style>
ul{
list-style-image:url('img/grey.png');
}
</style>

<body>

<ul>
  <li>Coffee</li>
  <li>Tea</li>
  <li>Coca Cola</li>
</ul>

</body>
</html>

list created seccessfully, but when I want using external style sheet and changed the code I have problem.

code:

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="css/styletest.css?version=2" ></head>

<body>

<ul>
  <li>Coffee</li>
  <li>Tea</li>
  <li>Coca Cola</li>
</ul>

</body>
</html>

style sheet:

ul{
list-style-image:url('img/grey.png');
}

image not show in second style.

thanks for any help.


Solution

  • You need to update the path to your image in your stylesheet. Paths in stylesheets are relative to the stylesheet.

    You're using a relative path that starts in the directory it is defined in.

    Your first, working, example suggests the following project structure.

    img/
     └── grey.png
    index.html
    

    img/grey.png is defined in index.html so the relative path starts looking for a directory named img that index.html is in. It finds it because both index.html and the img directory are in the same directory. Then continues on down the path to the file.

    Your second, non-working, example suggests the following project structure.

    css/
     ├── styletest.css
     └── img/
          └── grey.png
    index.html
    

    img/grey.png is defined in styletest.css so the relative path starts looking for a directory named img that styletest.css is in, which is in the css directory. It doesn't find img because it's not in the css directory. It's a level up from the css directory, like below.

    css/
     └── styletest.css
    img/
     └── grey.png
    index.html
    

    To move up a directory level from a current directory you need to use ../. Now the system will move up and out of the css directory and continue searching for the file from that directory and along the specified path.

    Change from

    list-style-image: url( 'img/grey.png' );
    

    to

    list-style-image: url( '../img/grey.png' );