How to center only one of the children inside a parent?

Viewed 86

I have two elements inside a div. How can I vertically center only p element?

.card {
  height: 300px;
  background-color: aquamarine;
}

<div class="card">
  <h1>Hello</h1>
  <p>Always in center vertically</p>
</div>

Edit intelligent-curran-b73ip

2 Answers

Use flex: display; and justify-content: center;. This will align the p tag to center.

Align h1 with position: absolute; to required position.

You should add position: relative; to .card for the h1 with style position: absolute; to stay inside .card

.card {
  height: 300px;
  background-color: aquamarine;
  display: flex;
  flex-direction: column;
  justify-content: center;
  position: relative;
  padding: 50px;
}

h1 {
  position: absolute;
  width: 100%;
  top: 0;
  background: beige;
  left: 0;
}
<h2>Sample App</h2>
<div class="card">
  <h1>Hello</h1>
  <p>Always in center vertically</p>
</div>

Since you want to vertically center <p> you can do that by using absolute position. First set your .card to position:relative; so that <p> remains inside it, now give .card p position:absolute; and set top:50%; but this will only center it to its parent element, to make it perfectly center we need to set transform:translateY(-50%);

  .card {
    height: 300px;
    background-color: aquamarine;
    position:relative;
  }
  .card p{
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
    margin: 0;
  }

If you want to make it horizontally center as well then all you need to do is add left:50%; & transform: translate(-50%, -50%); to .card p where you set both translate X and Y axis to -50%.

.card p{
    position: absolute;
    top: 50%;
    transform: translate(-50%,-50%);
    margin: 0;
  }
Related