1

I have the following grid layout:

 *       *   *       *
*********** ***********
 * Area1 *   * Area2 *
*********** ***********
 *       *   *       *

Both Area1 and Area2 are div elements. I want to add a background gradient spanning both Area1 and Area2. Is this possible?

I can surround them with another element spanning both Area1 and Area2, but then I can't place the children inside this grid layout.

I'm looking for a way to style multiple grid areas without nesting elements.

bkolobara
  • 71
  • 7
  • 1
    Yes, it's almost certainly possible; though the best way to achieve your aim depends on the HTML and CSS you're using. So if you want practicable answers from which you, and other future visitors, can learn then please supply some "*[mcve]*" code with which we can reproduce your scenario. Ideally share an image that you'd like to see used (if only as a demonstration) in the solution. – David Thomas Oct 06 '17 at 15:15
  • Related- https://stackoverflow.com/questions/46308048/how-to-target-a-specific-column-or-row-in-css-grid-layout – Paulie_D Oct 06 '17 at 15:19
  • If it's a linear gradient, then you should be able to split it into two halves (Two separate gradients, once for each element), which meet at the same colour in the middle. – DBS Oct 06 '17 at 15:35
  • @DBS...assuming there is no gap in the middle. :) – Paulie_D Oct 06 '17 at 15:36
  • @Paulie_D True, it's certainly not a bulletproof solution, but depending on OPs situation it may be an option :) – DBS Oct 06 '17 at 15:38

1 Answers1

4

No...CSS Grid areas are not DOM elements and so cannot be selected or styled by CSS

However, with CSS Grid, source order is not relevant and elements can be in the same "space" and layered using z-index without using positioning.

As such, a "styling div" (shudder) spanning the areas is possible.

.container {
  display: grid;
  grid-template-columns: 1fr 2fr 1fr 1fr;
  grid-gap: 1em;
  width: 80%;
  margin: auto;
  border: 1px solid red;
}

.container div {
  height: 175px;
  border: 1px solid grey;
  font-size: 2em;
  color:white;
}

.one {
  grid-row: 1;
  grid-column: 2/3;
}

.two {
  grid-row: 1;
  grid-column: 3/4;
}

.gradient {
  grid-column: 2/4;
  grid-row: 1;
  background: linear-gradient(to right, green, blue);
  z-index: -1;
}
<div class="container">
  <div class="one">Div 1</div>
  <div class="two">Div 2</div>
  <div class="gradient"></div>
</div>
Paulie_D
  • 107,962
  • 13
  • 142
  • 161