As a style of list items (with one class) individually

please help me create this list, I need to set a different background image for each list item, but the class is the same.

<ul>
<li class="sameforall">menu 1</li>
<li class="sameforall">menu 2</li>
<li class="sameforall">menu 3</li>
<li class="sameforall">menu 4</li>
</ul>

I know this one, but it only works for the fist element :(

ul:first-child li{
/*my css*/
} 
+3
source share
5 answers

Why would you give all one class?

Give ul the class contained by li, and then give li their own class, for example:

<ul class="sameforall">
   <li class="one">menu 1</li>
   <li class="two">menu 2</li>
   <li class="three">menu 3</li>
   <li class="four">menu 4</li>
</ul>

.sameforall {color: red;}
   .sameforall .one {background-color: blue;}
   .sameforall .two {background-color: green;}
   .sameforall .three {background-color: pink;}
   .sameforall .four {background-color: purple;}

You cannot access HTML, CSS3 support: nth-child () psuedo select - http://css-tricks.com/how-nth-child-works/

<ul>
   <li class="sameforall">menu 1</li>
   <li class="sameforall">menu 2</li>
   <li class="sameforall">menu 3</li>
   <li class="sameforall">menu 4</li>
</ul>

.sameforall:nth-child(1) { background-color: blue; }
.sameforall:nth-child(2) { background-color: green; }
.sameforall:nth-child(3) { background-color: pink; }
.sameforall:nth-child(4) { background-color: purple; }

Please note that this will not work in most older browsers.

+5
source

first-child, , , , . , - , . :

 <ul class="sameforall">
   <li id='first' >menu 1</li>
   <li id='second'>menu 2</li>
   <li id='third' >menu 3</li>
   <li id='forth' >menu 4</li> 
 </ul>

css, :

#first{/*Your css*/}

nth-child, , , .

+1

: nth-child() btw

ul li:fist-child
0

, CSS , JavaScript.

<ul>
    <li class="sameforall">menu 1</li>
    <li class="sameforall">menu 2</li>
    <li class="sameforall">menu 3</li>
    <li class="sameforall">menu 4</li>
</ul>
<script type="text/javascript">
    var listItems   = document.getElementsByTagName("ul")[0].getElementsByTagName("li");
    var numChildren = listItems.length; 
    for(var i = 0; i < numChildren; i++) {
        var item = listItems[i]; 

        // -> do whatever you want with each item.
        switch(i) {
            case 0: item.style.backgroundImage = 'url(item-1.gif);'; break;
            case 1: item.style.backgroundImage = 'url(item-2.gif);'; break;
            case 2: item.style.backgroundImage = 'url(item-3.gif);'; break;
        }            
    }
</script>
0

you need to go with the nth-child method.

The material here is very detailed. Hope this helps you.

http://www.w3.org/TR/css3-selectors/

0
source

Source: https://habr.com/ru/post/1750479/


All Articles