Tuesday, April 10, 2018

Display dynamic background color using CSS

By using CSS 3 we can make may design like as dynamic.

here, we will discuss regarding how to display dynamic CSS by using ":nth-child" structural pseudo-class. The :nth-child selector allows you to select one or more elements based on their source order and as per selector.

EX: demo
<!DOCTYPE html>
<html>

<title>Display dynamic background color using CSS</title>

<head>
    <style>
    .my_list {
        margin: 5px;
    }

    .my_list:nth-child(1n) {
        background-color: fuchsia
    }

    .my_list:nth-child(2n) {
        background-color: green
    }

    .my_list:nth-child(3n) {
        background-color: grey
    }

    .my_list:nth-child(4n) {
        background-color: cyan
    }

    .my_list:nth-child(7n) {
        background-color: orange
    }
    </style>
</head>

<body>
    <h1>My list with different background color.</h1>
    <div class="my_list"> my list 1 </div>
    <div class="my_list"> my list 2 </div>
    <div class="my_list"> my list 3 </div>
    <div class="my_list"> my list 4 </div>
    <div class="my_list"> my list 5 </div>
    <div class="my_list"> my list 6 </div>
    <div class="my_list"> my list 7 </div>
    <div class="my_list"> my list 8 </div>
    <div class="my_list"> my list 9 </div>
    <div class="my_list"> my list  10</div>
</body>

</html>

Output

My list with different background color.

my list 1
my list 2
my list 3
my list 4
my list 5
my list 6
my list 7
my list 8
my list 9
my list 10

in the above example, the first element will display with fuchsia color, the second element will display with green color and so on.

in this, every third, fourth and seventh will overwrite the first and second background color. here we can use any value in nth-child() element like 1n, 2n, 3n, ... to effect matched element.

By using this structural pseudo-class we can display dynamic or specific element affected CSS class.

No comments:

Post a Comment