Home > Back-end >  What's the best way to set background color to a grid row in a HTML layout
What's the best way to set background color to a grid row in a HTML layout

Time:09-22

I have a grid with two rows and three columns that looks like the image bellow.

I'm using the following CSS properties for the grid:

.grid-container{
  display:grid;
  grid-template-columns: 20vw 60vw 20vw;
  grid-template-rows:100px calc(100vh - 100px);
}

I could just do the following to set the background color of the first row to white:

.grid-container > div:nth-child(1),
                  div:nth-child(2),
                  div:nth-child(3) {
  background: white;
}

But is this a good approach ? Is there a way to color the grid template row directly in the .grid-container class ??

enter image description here

Snippet

body{margin:0}
.grid-container{
  display:grid;
  grid-template-columns: 20vw 60vw 20vw;
  grid-template-rows:100px calc(100vh - 100px);
}
.grid-container > div:nth-child(1),
                  div:nth-child(2),
                  div:nth-child(3) {
  background: blue;
}
.grid-container > div {
  border:1px solid black;
}
<div >
        
  <!-- header -->
  <div></div>
  <div></div>
  <div></div>

  <!-- main content -->
  <div></div>
  <div></div>
  <div></div>
        
</div>

CodePudding user response:

Best way = use a class selector.

body {
  margin: 0
}

.grid-container {
  display: grid;
  grid-template-columns: 20vw 60vw 20vw;
  grid-template-rows: 100px calc(100vh - 100px);
}

.first-row {
  background: blue;
}

.first-row.third {
  background-color: lightblue;
}

.grid-container>div {
  border: 1px solid black;
}

.main {
  background-color: orange;
}
<div >

  <!-- header -->
  <div ></div>
  <div ></div>
  <div ></div>

  <!-- main content -->
  <div ></div>
  <div ></div>
  <div ></div>

</div>

  • Related