I am using CSS Grid, which works great, but want to have a background SVG that the grid sits on top of.
For example, here is the HTML:
<div className="wrapper">
<div className="item">
<div id="wave">
<svg viewBox="0 0 500 200" preserveAspectRatio="none"><path d="M0.00,92.27 C216.83,192.92 304.30,8.39 500.00,109.03 L500.00,0.00 L0.00,0.00 Z"></path></svg>
</div>
</div>
<div className="item">1</div>
<div className="item">2</div>
<div className="item">3</div>
</div>
...and the CSS:
.wrapper {
display: grid;
grid-template-rows: 100px 100px 100px 100px;
grid-template-columns: 100vw;
gap: 10px;
width: 100vw;
height: auto;
}
.item {
background: rgba(0, 0, 0, 0.5);
}
...which obviously only places the SVG in the top row. How can I sit the SVG behind the grid? I also tried wrapping the wrapper with a div and seeing the position to absolute.
Should look like this (svg wave in blue, grid items in pink):
CodePudding user response:
Using the wrapper approach:
- Create a wrapper element with
position: relative
. - Add the
svg
element withposition: absolute
andtop: 0
,right: 0
, etc... - Add the grid element with
position: relative
.
The wrapper having position: relative
allows the svg
to size itself using the wrapper as its parent. The position: relative
on the grid creates a new stacking context above the svg
which also has its own stacking context thanks to position: absolute
.
Here's a demo:
.wrapper {
position: relative;
}
.wrapper svg {
position: absolute;
top: 0; right: 0; bottom: 0; left: 0;
fill: lightblue;
}
.grid {
display: grid;
grid-template-rows: 100px 100px 100px 100px;
grid-template-columns: 100%;
border: 1px solid black;
gap: 10px;
position: relative;
}
.item {
background-color: rgba(0, 0, 0, 0.5);
}
<div class="wrapper">
<svg viewBox="0 0 500 200" preserveAspectRatio="none">
<path d="M0.00,92.27 C216.83,192.92 304.30,8.39 500.00,109.03 L500.00,0.00 L0.00,0.00 Z"></path>
</svg>
<div class="grid">
<div class="item">1</div>
<div class="item">2</div>
<div class="item">3</div>
<div class="item">4</div>
</div>
</div>