Spirconi
Spirconi

Reputation: 214

CSS Grid inside Max-width Container

I have a parent section div with a max-width of 1760px.

I can put a carousel directly inside a section container and it will take the width of the viewport up to 1760px i have set, works as expected. *carousel will try to fill 100% of space given.

However, the issue is that i want to put the content inside a 2 col grid, inside container, but the first part of the grid has the carousel that takes the max-width of parent section, rather than stopping at width of page. So, rather than take 2fr of the viewport (map takes 1fr), it fills whole of 1760px so the screen overflows.

Style wise, The best example i can find online to show what i mean is Airbnb listing, it has 2 cols, 1 with listing and 1 with map. This is pretty much what i am trying to replicate.

Here is the carousel directly in section (pretty simple and works as explained above). If i put the carousel inside this it doesn't overflow page.

<section>
    <div>Carousel</div>
</section>

section{
     max-width: 1760px;
     padding: 50px 40px;
     margin: 0 auto;
}

Once i add it inside a grid it ignores the viewport size and simply fills max-width of section (1760px) and overflows viewport width.

<section>
    <div class="grid">
        <div>Carousel</div>
        <div>Map</div>
    </div>
</section>

.grid{
    display: grid;
    grid-template-columns: 2fr 1fr;
    grid-gap: 20px;
}

It actually works using grid-template-columns: 60% 40%; instead of 2fr 1fr, and removing margin: 0 auto. But this means i cannot use gap (which is fine).

To summerize, how can i use fr sizing and make sure it takes notice of viewport size, and not just take up the max-width value by default.

Upvotes: 0

Views: 1664

Answers (1)

Prathamesh Koshti
Prathamesh Koshti

Reputation: 1360

I went through your pen and made some changes and it gave the result as you wanted it to be, no overflowing of the image.

If you do following changes, it will work for you too:

  1. These are not mandatory, if you wish you can do the changes or else you can keep as it is.
  • Remove the max-width: 1760px from section style.
  • Add max-width: 1760px to the grid element, since you are providing the max-width to the grid, the parent section will also have this max-width, since grid is the child element.
  1. Now make sure you are applying the width: 100% to the images (This is mandatory). Like this:
.listing > img {
  width: 100%;
}

OR, if you have nested elements inside .listing element and img tag is not the immediate child of the .listing element, then you can go with this way:

.listing img {
  width: 100%;
}

So every img tag which is direct or indirect descendent of .listing element will have width 100%

Here's the working piece of example: https://codepen.io/prathameshkoshti/pen/KKMYoWY?editors=0100

Upvotes: 0

Related Questions