Home > OS >  Center div by specific item
Center div by specific item

Time:01-25

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 >
<div >
  <p >Lorem ipsum</p>
  <p>Center this</p>
  <p >Lorem ipsum</p>
</div>
</div>

CodePudding user response:

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 >
<div >
  <p >Lorem ipsum</p>
  <p >Center this</p>
  <p >Lorem ipsum</p>
</div>
</div>

CodePudding user response:

Assuming you mean center horizontally, you just need to expand the child container with flex-grow and use align-self on your chosen child:

.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;
    flex-grow: 1;
    align-items: flex-start;
  }

  .child-container * {
    background-color: greenyellow;
  }

  .big {
    line-height: 40px;
  }

  .bigger {
    line-height: 80px;
  }

  .center {
    align-self: center;
  }
<div >
<div >
  <p >Lorem ipsum</p>
  <p >Center this</p>
  <p >Lorem ipsum</p>
</div>
</div>

  • Related