Applying CSS to one row of grid-template-areas

Viewed 129

I am new to coding. I'm working on a beginner's project where I am trying to replicate Google's Advanced Search page. I am making the header using display: grid; and want to apply background colors to individual rows.

#header{
    display: grid;
    grid-template-columns: 100px 1fr 50px;
    grid-template-rows: 50px 200px;
    grid-template-areas:
    "google-logo . search"
    "advanced-search . ."
    }

In the above example, I want the row with google-logo . search to have a background color of gray. Any help would be appreciated, thank you!

2 Answers

you could add a class to these columns, for example:

<div id="header">
  <div class="item1 bg-gray">1</div>
  <div class="item2 bg-gray">2</div>
  <div class="item3">3</div>
</div>

and having your css like this:

.bg-gray {
  background-color: gray
}

working snippet:

#header {
  display: grid;
  grid-template-columns: 100px 1fr 50px;
  grid-template-rows: 50px 200px;
  grid-template-areas: "google-logo . search" "advanced-search . ."
}

.bg-gray {
  background-color: gray;
}
<div id="header">
  <div class="item1 bg-gray">1</div>
  <div class="item2 bg-gray">2</div>
  <div class="item3">3</div>
</div>

You can use an element - or pseudo element like below - to color specific row.

#header {
  height: 300px;
  display: grid;
  grid-template-columns: 100px 1fr 50px;
  grid-template-rows: 50px 200px;
  grid-template-areas: "google-logo . search" "advanced-search . ."
}

#header::before {
  content:'';
  background:gray;
  grid-column: google-logo / search;
  grid-row: google-logo / search;
}

/* others */

#header div:nth-child(1) {
  background: yellow;
  grid-area: google-logo;
  margin:5px;
}

#header div:nth-child(2) {
  background: red;
  grid-area: search;
  margin:5px;
}

#header div:nth-child(3) {
  background: blue;
  grid-area: advanced-search;
}
<div id="header">
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</div>

Related