Search code examples
htmlcsscss-grid

Full width background with viewport-centered grid layout


I have a simple grid layout to display a single column of elements like this:

body
{
    display: grid;
    justify-content: center;
    grid-auto-flow: row;
}

body > * {
    width: 75vw;
    max-width: 45rem;
}

body's children are header, main and footer. I would like to define a background (color) for the header to cover the full width of the viewport without its content overflowing the area defined by the CSS instructions above. I found a couple of answers pointing to pseudo elements, but they seem to require a different grid setup. Is there any simple way to get the full width background color without complicating the very elegant CSS too much?


Solution

  • Use border-image: https://css-tip.com/overflowing-background/

    body {
      display: grid;
      justify-content: center;
    }
    
    body > * {
      width: 75vw;
      max-width: 45rem;
      padding-block: 1em;
    }
    
    main {
     border-image: conic-gradient(lightblue 0 0) fill 0//0 100vw;
    }
    <header>
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras a justo interdum, gravida tellus quis, iaculis tortor. Suspendisse quis lectus scelerisque, porta felis in, faucibus dui. Vivamus lobortis pellentesque urna vel ornare. Nulla est purus, tincidunt a ante in, efficitur commodo massa. Curabitur ultrices mollis</header>
    <main>
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras a justo interdum, gravida tellus quis, iaculis tortor. Suspendisse quis lectus scelerisque, porta felis in, faucibus dui. Vivamus lobortis pellentesque urna vel ornare. Nulla est purus, tincidunt a ante in, efficitur commodo massa. Curabitur ultrices mollis</main>
    <footer>
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras a justo interdum, gravida tellus quis, iaculis tortor. Suspendisse quis lectus scelerisque, porta felis in, faucibus dui. Vivamus lobortis pellentesque urna vel ornare. Nulla est purus, tincidunt a ante in, efficitur commodo massa. Curabitur ultrices mollis</footer>