Search code examples
htmlcssresponsive-designmargin

How to make a child element wider than its parent div, but not fill the entire browser width and be responsive?


I'm using negative margins to make a child element (.alignwide with width = 1000px) wider than its parent div (.wrapper with width = 800px), but I don't want it to fill the entire browser width. This is the code I'm using:

HTML:

<div class="wrapper">
    <div class="alignwide">
        This div expands beyond .wrapper parent margins. 
    <div>
</div>

CSS:

.wrapper {
    max-width: 800px;
    width: 100%;
    margin: 0 auto;
}

.alignwide {
    margin-left: calc((100% - 1000px) / 2);
    margin-right: calc((100% - 1000px) / 2);
    width: auto;
}

This is working if the browser window is wider than 1000px, but when I resize it to be narrower than 1000px, the .alignwide div is not responsive and its contents get cropped. Is there a way to make the .alignwide div narrower when reducing the browser width?

UPDATE: I'm adding two screenshots showing the behavior I'm looking for:

When the browser width is wider than 1000px: enter image description here

When the browser width is narrower than 1000px: enter image description here

Thanks in advance


Solution

  • Use min() to take the minimum value between 1000px and the screen width (100vw). I am using margin-inline which is as shorthand for left/right margin.

    .wrapper {
      max-width: 800px;
      margin:auto;
    }
    
    .alignwide {
      margin-inline: calc((100% - min(100vw,1000px)) / 2);
      background: red;
    }
    <div class="wrapper">
      <div class="alignwide">
        This div expands beyond .wrapper parent margins.
      </div>
    </div>