how do I make a container offset to the left at a particular point and fill the remaining space in css

Viewed 562

For example, .container-a has these styles:

.container-a {
  max-width: 1240px;
  margin: 0 auto;
}

This means that .container-a will never exceed the defined width of 1240px. The left and right auto margins mean the browser automatically calculates equal margins on the left and right side which makes it always centered no matter how large the screen gets.

Now, say I want to have another container. This container-b should offset the same left margin that .container-a offsets to the left which means both .container-a and .container-b start at the same point. The only difference is that this particular container-b doesn't offset a right margin and does not have a defined maximum width which means it fills the remaining available space on the browser window irrespective of how large the screen gets. Is that possible and how do I achieve that?

2 Answers

Instead of absolute positioning as suggested in the other answers, I would go with calc() here, which allows you to do some basic math in CSS. (Absolute positioning is not a tool for basic layouting, and can lead to a lot of other issues with the rest of the document flow.)

The trick is to simply divide the available window width (100%) in half, subtract half of the max-width of container a - and then set that as margin-left for container b.

I went with a smaller max-width of 500px here, so that the effect is easily visible here in the rendered snippet, but you can easily modify this accordingly, for the max-width you actually need.

div {
  background: #ccc;
}

.container-a {
  max-width: 500px;
  margin: 1em auto;
}

.container-b {
  margin: 1em auto;
  margin-left: calc(100% / 2 - 250px) /* 250px = half the max-width of container a */
}
<div class="container-a">
  I am container-a
</div>
<div class="container-b">
  I am container-b
</div>

You might want to wrap this into a media query, so that it doesn’t misbehave when the available window width is smaller than the max-width (because that would result in a negative margin-left for container b here.)

you can do something like this:

<div class='c'>
  <div class='c1'>container</div>
  <div class='c2'>container</div>
</div>

.c {
  width: 400px;
  margin: 0 auto;
}
.c1 {

  background: red;
  margin: 0 auto;
}
.c2 {
  background: blue;
  position: absolute;
  width: 100%;
}
Related