Home > front end >  Align two flex items vertically independent of each other
Align two flex items vertically independent of each other

Time:02-14

Inside the container are two elements "Title" and "Signature". Their vertical position will be taken from the given parameters and added to the mustache template, i.e. can be anything, for example:

  • title and caption top/center/bottom;
  • title at the top, caption at the center;
  • title centered, caption bottom;
  • title at the top, caption at the bottom, etc.

If I do it through the lines, then the captions either stick to the headings (when they are on the same vertical) or the indentation is visible along the width of the heading content. If I do through the columns - nothing happens at all. Can anyone suggest to align several elements vertically, but so that they do not stick together and do not run into each other?

.item {
  display: flex;
  align-items: flex-start;
  border: 5px solid yellow;
  background-color: #bbb;
  height: 200px;
}
  <div >
     <div  style="align-self: flex-start;">Title lorem ipsum  lorem ipsum  lorem ipsum  lorem ipsum  lorem ipsum  lorem ipsum  lorem ipsum</div>
     <div  style="align-self: center;">Caption caption caption</div>
  </div>
  
    <div >
     <div  style="align-self: center;">Title lorem ipsum  lorem ipsum  lorem ipsum  lorem ipsum  lorem ipsum  lorem ipsum  lorem ipsum</div>
     <br>
     <div  style="align-self: center;">Caption caption caption</div>
  </div>
  
      <div >
     <div  style="align-self: center;">Title lorem ipsum  lorem ipsum  lorem ipsum  lorem ipsum  lorem ipsum  lorem ipsum  lorem ipsum</div>
     <br>
     <div  style="align-self: flex-end;">Caption caption caption</div>
  </div>

UPD: Added an image of how it should look like in the end enter image description here

CodePudding user response:

You can make use of justify-self and align-self for variant 2 and 3. Everything else is basic flexbox and grid which you can learn here and here.

*{
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}
body{
  display: flex;
  flex-wrap: wrap;
  margin: 1rem;
  gap: 1rem;
}
.variant{
  padding: 1rem;
  background-color: #6D6A89;
  height: 25rem;
  width: 250px;
  color: #fff;
}

.var1{
  display: flex;
  flex-direction: column;
  align-items: center;
}

.var2{
  display: grid;
}
.var2>*{
  justify-self: center;
}

.var3{
  display: grid;
}

.var3>*{
  align-self: end;
  justify-self: center;
}

.var4{
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: space-between;
}
<body>
  <div >
    <h1>Title top</h1>
    <div >caption top</div>
  </div>
  <div >
    <h1>Title top</h1>
    <div >caption center</div>
  </div>
  <div >
    <h1>Title center</h1>
    <div >caption bottom</div>
  </div>
  <div >
    <h1>Title top</h1>
    <div >caption bottom</div>
  </div>
</body>

More on flexbox here.

  • Related