Search code examples
javascripthtmlcssflexboxgrid

Center div by specific item


Is it possible to center not the whole child-container div but by an specific item. The content of the first p and last p have different heights and can change dynamically.

.container {
  display:flex;
  align-items: center;
  height: 300px;
  background-color: red;
}

.child-container {
  display: flex;
  flex-direction: column;
  justify-content: space-evenly;
  background-color: purple;
}

.big{
  line-height:40px;
}

.bigger{
  line-height:80px;
}
<div class="container">
<div class="child-container">
  <p class="big">Lorem ipsum</p>
  <p>Center this</p>
  <p class="bigger">Lorem ipsum</p>
</div>
</div>


Solution

  • Give the child container a position of relative and the center paragraph absolute. Then give the center paragraph a margin top and bottom of 50vh:

    .container {
      display:flex;
      align-items: center;
      height: 300px;
      background-color: red;
    
    }
    
    .child-container {
      display: flex;
      flex-direction: column;
      justify-content: space-evenly;
      background-color: purple;
        position: relative;
    }
    
    .big{
      line-height:40px;
    }
    
    .bigger{
      line-height:80px;
    }
    
    .center {
        position: absolute;
        margin-top: 50vh;
        margin-bottom: 50vh;
    }
    <div class="container">
    <div class="child-container">
      <p class="big">Lorem ipsum</p>
      <p class="center">Center this</p>
      <p class="bigger">Lorem ipsum</p>
    </div>
    </div>