0

In ahref I have div element. That div has background image and under div I am displaying h3 text.

I want h3 text to be vertically center aligned but I am unable to do it. Please help me.

Below is my html and style code.

<html>
<head>
<style>
.promo-item {
    height: 400px;
}
.promo-item h3 {
    font-size: 40px;
    text-align: center;
}

.item-1 {
    background: url('images/mung_beans.jpg');
    }
    
.item-2 {
    background: url('images/coffee_beans_1.jpg');
    }
    
.item-3 {
    background: url('images/grapes.jpg');
    }
        
.item-1,
.item-2,
.item-3 {
    width: 33%;
    background-size: cover;
    background-position: 50% 50%;
    float:left;
    }
    
</style>
</head>
<body>
    <div>
        <a href="#">
            <div class="promo-item item-1">
                <h3>One</h3>
            </div>
        </a>
        <a href="#">
            <div class="promo-item item-2">
                <h3>Two</h3>    
            </div>
        </a>
        <a href="#">
            <div class="promo-item item-3">
                <h3>Three</h3>
            </div>
        </a>
    </div>
</body>
</html>
userrmgs
  • 193
  • 7

1 Answers1

1

Use flexbox and set the align-items and justify-content properties to center.

.promo-item {
  height: 400px;
}

.promo-item h3 {
  font-size: 40px;
  text-align: center;
}

.item-1 {
  background: lightgrey;
}

.item-2 {
  background: lightgrey;
}

.item-3 {
  background: lightgrey;
}

.item-1,
.item-2,
.item-3 {
  width: 33%;
  background-size: cover;
  background-position: 50% 50%;
  float: left;
  display: flex;
  align-items: center;
  justify-content:center;
}
<html>

<body>
  <div>
    <a href="#">
      <div class="promo-item item-1">
        <h3>One</h3>
      </div>
    </a>
    <a href="#">
      <div class="promo-item item-2">
        <h3>Two</h3>
      </div>
    </a>
    <a href="#">
      <div class="promo-item item-3">
        <h3>Three</h3>
      </div>
    </a>
  </div>
</body>

</html>
Spectric
  • 5,761
  • 2
  • 6
  • 27
  • If I use display:flex; and align-items: center;, the h3 text is vertically aligned but not horizontally aligned. How to make text both vertically and horizontally center aligned. – userrmgs May 11 '21 at 02:12
  • @userrmgs I've updated my answer. Use `justify-content:center` – Spectric May 11 '21 at 02:13
  • it is working. Thank you – userrmgs May 11 '21 at 02:16
  • @userrmgs Please consider accepting my answer :). [How to accept an answer](https://meta.stackexchange.com/questions/86978/how-do-i-accept-an-answer-on-stackoverflow) – Spectric May 11 '21 at 02:17