简体   繁体   中英

Can I change CSS style after HTML load in multiple places

I have HTML code the loads a grid of images. The images have a box-shadow around them. Each image is loaded one by one on the grid, but they are all using the same style sheet. I want to make each box-shadow a different colour for the images. Is this possible?

I tried to test this a simple way by making each alternate image's shadow a different colour, but it only uses the last image's colour that is loaded for all of the images. Here is how I tested it:

//i is defined outside this
if($i == 0){
    //I am using PHP to print out the HTML
    Echo "<style> ul.rig li { box-shadow: 0 0 10px #2de61c; }</style>";
    $i++;
}else if($i == 1){
    Echo "<style> ul.rig li { box-shadow: 0 0 10px #ed1515; }</style>";
    $i--;
}

Whatever i equals for the last loaded image, the rest of the image's shadows will have that colour. Is it possible to alternate/have different colours like this?

Just use nth-child CSS.

ul.rig li:nth-child(odd) { box-shadow: 0 0 10px #2de61c; }
ul.rig li:nth-child(even) { box-shadow: 0 0 10px #ed1515; }

https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-child

Why not use something like:

 //i is defined outside this
 if($i == 0){
     //I am using PHP to print out the HTML
     Echo "<htmlselector class="1"></htmlselector>";
     $i++;
 }else if($i == 1){
     Echo "<htmlselector class="1x"</htmlselector>";
     $i--;
 }

This way you can use CSS and style them accordingly.

You could load images into that grid together with a certain class. Then give each of those classes a preferred style. Because what you do now is just overriding css.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM