2

What's the best way to shrink-wrap a div using flex-box? In the snippet below, I have a wrapper (the green border) shrink-wrapping the content (red & blue boxes) on all sides but the bottom.

How can I get this accomplished?

Here's a plunker demo: https://plnkr.co/edit/u89JPIbZObTYIfRejlO1?p=preview

.red {
  width: 100px;
  height: 50px;
  background-color: red;
}

.blue {
  width: 100px;
  height: 50px;
  background-color: blue;
}

.container2 {
  width: 400px;
  height: 300px;
  border: solid;
  display: flex;
  justify-content: center;
}

.wrapper2 {
  border: solid green;
  padding: 5px;
}
<div class="container2">
  <div class="wrapper2">
    <div class="red">x</div>
    <div class="blue">x</div>
  </div>
</div>
Skyler
  • 777
  • 1
  • 9
  • 34

2 Answers2

1

you can use :

  • align-items
.container2 {
  width: 400px;
  height: 300px;
  border: solid;
  display: flex;
  justify-content: center;
  align-items:flex-start;/* update here */
}

.red {
  width: 100px;
  height: 50px;
  background-color: red;
}

.blue {
  width: 100px;
  height: 50px;
  background-color: blue;
}

.container2 {
  width: 400px;
  height: 300px;
  border: solid;
  display: flex;
  justify-content: center;
  align-items:flex-start;
}

.wrapper2 {
  border: solid green;
  padding: 5px;
  /*margin:0 auto auto*/
}
<div class="container2">
  <div class="wrapper2">
    <div class="red">x</div>
    <div class="blue">x</div>
  </div>
</div>
  • or margin
.wrapper2 {
  border: solid green;
  padding: 5px;
  margin:0 auto auto/* update here */
}

.red {
  width: 100px;
  height: 50px;
  background-color: red;
}

.blue {
  width: 100px;
  height: 50px;
  background-color: blue;
}

.container2 {
  width: 400px;
  height: 300px;
  border: solid;
  display: flex;
  justify-content: center;
 /* align-items:flex-start;*/
}

.wrapper2 {
  border: solid green;
  padding: 5px;
  margin:0 auto auto
}
<div class="container2">
  <div class="wrapper2">
    <div class="red">x</div>
    <div class="blue">x</div>
  </div>
</div>

a reminder/titorial: https://css-tricks.com/snippets/css/a-guide-to-flexbox/

G-Cyrillus
  • 101,410
  • 14
  • 105
  • 129
1

Use the align-items: flex-start; property on .container2

.red {
  width: 100px;
  height: 50px;
  background-color: red;
}

.blue {
  width: 100px;
  height: 50px;
  background-color: blue;
}

.container2 {
  width: 400px;
  height: 300px;
  border: solid;
  display: flex;
  justify-content: center;
  align-items: flex-start;
}

.wrapper2 {
  border: solid green;
  padding: 5px;
}
<div class="container2">
  <div class="wrapper2">
    <div class="red">x</div>
    <div class="blue">x</div>
  </div>
</div>
Varin
  • 2,354
  • 2
  • 20
  • 37