Home > Enterprise >  Margin 0 auto for a CSS Grid layout with Image that occupies the entire right side
Margin 0 auto for a CSS Grid layout with Image that occupies the entire right side

Time:12-24

I was trying to come up with a consistent way to ensure that the white space is the same for all containers like so:

enter image description here

Note: The grey rectangle represents an image. I am trying to get it to stretch all the way to the end of the viewport, starting from its respective column.

This is the code I have so far:

HTML:

<div >
    <h1>Title</h1>
    <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
</div>


<div >
    <div >
        <h2>Title</h2>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
    </div>

    <div >
        <img src="https://w.wallhaven.cc/full/9m/wallhaven-9mjoy1.png" alt="" />
    </div>
</div>

CSS / SCSS:

.container {
   max-width: 127rem;
   margin: 0 auto;
}


.grid {
   display: grid;
   grid-template-columns: repeat(2, 1fr);
   grid-gap: 3rem;

   &__content-wrapper {
   }

   &__image-wrapper {
   }

   &__img {
      display: block;
      width: 100%;
      height: auto;
   }
}

I am trying to figure out a way to have the margin on the left of the .grid section to consistently match the section in the .container layout but have the image ignore the max-width and stretch all the way to the end of the grid. I have no idea to go about it. Could anyone help point me in the right direction?

CodePudding user response:

This works but you need to make sure your body margin is set to 0 otherwise it nudges the grid item in by the margin width. You also have to set up a css variable for the max width in the root element. Hope this helps. Note you have to see it in full screen mode, the snippet viewer does something funny in the previewer.

:root {
  --max-width: 600px;
}

/* added this */
body {
  margin:0;
}

.container {
  /* use css variable defined above */
  max-width: var(--max-width);
  margin: 0 auto;
}

.grid {
  /* added these */
  margin-block: 0;
  margin-left: max(0px, calc(50vw - calc(var(--max-width) / 2)));

  display: grid;
  grid-template-columns: repeat(2, 1fr);
  grid-gap: 3rem;
}

.grid__img {
  display: block;
  width: 100%;
  height: auto;
}
<div >
    <h1>Title</h1>
    <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
</div>

<div >
    <div >
        <h2>Title</h2>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
    </div>

    <div >
        <img src="https://w.wallhaven.cc/full/9m/wallhaven-9mjoy1.png" alt="" />
    </div>
</div>

  • Related