bunny
bunny

Reputation: 2037

How can I set a customized distance between child of flexbox

enter image description here

<div class="container">
    <div class="a"></div>
    <div class="b"></div>
    <div class="c"></div>
</div>

.container{
    display: flex;
    flex-direction: column;    
    justify-content: space-between;
    height: 140;
}


.a{
    margin-top: 10px;
    height: 17px;
}

.b{
    //??
    height: 40px;
}

.c{
    margin-bottom: 10px;
    height: 18px;
}

I have three <div>s a, b and c in the container <div>. I want an element a to be positioned 10px to the top of the container, b to be positioned 50px to the top of the container and c to be positioned 10px to the bottom of the container. How should I set b's style in order to achieve this? I want to avoid using absolute position if possible since when I tried to use it, somehow the width of b changed. I want to know if there is a way to set a customized distance between children of a flexbox.

Upvotes: 1

Views: 71

Answers (1)

kukkuz
kukkuz

Reputation: 42352

Its easier that you adjust the distances here with margins - so you can remove justify-content: space-between.

Add margin-top: 23px to b and margin-top: auto to c. Check the below demo (you can inspect the red lines to verify that the distances are correct):

* {
  box-sizing: border-box;
}
.container {
  display: flex;
  flex-direction: column;
  /*justify-content: space-between;*/
  height: 140px;
  border: 1px solid;
  position: relative;
}
.a {
  margin-top: 10px;
  height: 17px;
}
.b {
  height: 40px;
  margin-top: 23px;  /* ADDED */
}
.c {
  margin-bottom: 10px;
  height: 18px;
  margin-top: auto; /* ADDED */
}

/* STYLING */
.a,.b,.c {
  border: 1px solid blue;
  background: cadetblue;
}
.a:before,.b:before,.c:before {
  content: '';
  top: 0;
  width: 2px;
  position: absolute;
  left: 100px;
  background: red;
}
.a:before {
  height: 10px;
}
.b:before {
  height: 50px;
  left: 200px;
}
.c:before {
  left: 100px;
  top: unset;
  bottom: 0;
  height: 10px;
}
<div class="container">
  <div class="a"></div>
  <div class="b"></div>
  <div class="c"></div>
</div>

Upvotes: 2

Related Questions