bblocs3141
bblocs3141

Reputation: 133

Margin + ? = 100% width in flexbox

I have a flexbox with a width of 80vw and content inside of it align-items: center and justify-content: center. All the items in the column have 28px margin on either side. Right now, they are very skinny and only take up a part of the 80vw. Inspecting it shows a large amount of whitespace on either side.

I still want stuff like text centered, but things like a selection box should take up the full width of the container (including margins).

I've read a few things on here, and I've tried setting width: 100% but that not only disregards the centering css (pushes the item all the way to the left) but also disregards margins, and the margins spill over out of the width of the container.

Finally, I tried calc and calculated 80vw - 28px as the width of the inner content, but this did some weird stuff and only used half the margin, and the rest of it spilled out of the container.

enter image description here

.outerContainer {
  display: flex;
  align-items: center;
  justify-content: center;
  position: absolute;
  width: 100vw;
  height: 100vh;
  background-color: black;
}

.modalContainer {
  width: 80vw;
  background-color: white;
  z-index: 2;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
}
 
.content1 {
  margin: 20px 28px 10px 28px;
  font-size: 27px;
  line-height: 21px;
}

.content2 {
  margin: 10px 28px 20px 28px;
}
 
 
<html>
  <body>
    <div class="outerContainer">
      <div class="modalContainer">
        <div class="content1">
          Hello, World!
        </div>
        <div class="content2">
           <input type="text" />
        </div>
      </div>
    </div>
  </body>
</html>

Upvotes: 1

Views: 2426

Answers (1)

Pete
Pete

Reputation: 58452

You can make the content divs 100% width minus margin by using the calc function (comments added to the lines I changed below):

.outerContainer {
  display: flex;
  align-items: center;
  justify-content: center;
  position: absolute;
  width: 100vw;
  height: 100vh;
  background-color: black;
}

.modalContainer {
  width: 80vw;
  background-color: white;
  z-index: 2;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
}
 
.content1 {
  margin: 20px 28px 10px 28px;
  font-size: 27px;
  line-height: 21px;
}

.content2 {
  margin: 10px 28px 20px 28px;
  width: calc(100% - 56px);    /* 100% width minus 28px x 2 */
}


.content2 > input {
    width:100%;              /* make input stretch full width */
}
<html>
  <body>
    <div class="outerContainer">
      <div class="modalContainer">
        <div class="content1">
          Hello, World!
        </div>
        <div class="content2">
           <input type="text" />
        </div>
      </div>
    </div>
  </body>
</html>

Upvotes: 5

Related Questions