Home > Net >  Bootstrap CSS Different Color on col-md Newline
Bootstrap CSS Different Color on col-md Newline

Time:07-26

I have a responsive website, using bootstarp. In one of the pages I have a simple list of divs, like so:

<div >
<div ><div >1</div></div>
<div ><div >2</div></div>
<div ><div >3</div></div>
<div ><div >4</div></div>
:
:
<div ><div >20</div></div>
</div>

The frontend is using react, if that matters. I am looking to implement a feature where each new line will have a different color.

I don't know how many items there will be, but I know the upper limit should be around 20 (so with col-md-3, it means 5 rows).

But I have seen that for small screens, sometimes bootstrap breaks the row after 3 items, not 4.

Is there a way to achieve different color per row?

CodePudding user response:

Okay, you can use this for different column colors.

style="background-color: #4e3836;"

How can you do this in your code? Here is an example.

<div  style="background-color: #4e3836;"><div >1</div></div>
<div  style="background-color: #fff;"><div >2</div></div>
<div  style="background-color: #00000;"><div >3</div></div>
<div  style="background-color: #4e3853;"><div >4</div></div>

CodePudding user response:

in first time, you need a class in your div.

After that you can do what you want with for boucle.

document.addEventListener('DOMContentLoaded', function() {

    let div_line = document.getElementsByClassName('myColor');

    for(i = 0; i < div_line.length; i  ) {
        if(i <= 4){
            let newLine = div_line[i] ;
            newLine.style.backgroundColor = 'blue';
        }
        if(i >= 4 && i < 8){
            let newLine = div_line[i] ;
            newLine.style.backgroundColor = 'red';
        }
        console.log(div_line.lenght);
        console.log(i)
    }

});
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
    <script src="scripts.js"></script>
    <title>Document</title>
</head>
<body>
    <div >
        <div ><div >1</div></div>
        <div ><div >2</div></div>
        <div ><div >3</div></div>
        <div ><div >4</div></div>
        :
        :
        <div ><div >20</div></div>
    </div>
</body>
</html>
Don't forget repeat the script to continu to 20 lines.

You can delete my console.log, this is for test.

  • Related