search

Home  >  Q&A  >  body text

Is there a way to force the text in the flexbox to be vertically centered, no matter what other CSS code we have?

I have the following CSS code that is part of a larger CSS code used in a website I'm developing:

.cards-u {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  align-items: center;
}

.card-u {
  margin: 20px;
  padding: 20px;
  width: 160px;
  height: 160px;
  line-height: 120px;
  justify-content: center;
  align-items: center;
  text-align: center;
  align-self: center;
  flex-direction: column;
  border-radius: 10px;
  box-shadow: 0px 6px 10px rgba(0, 0, 0, 0.25);
  transition: all 0.2s;
  text-decoration: none;
}

.card-1-u {
  background: radial-gradient(#1fe4f5, #3fbafe);
}

In the HTML code I have:

<div class="cards-u">
 <a href="https://example.com" class="card-u card-1-u" style="text-decoration: none;">
   <h3>Text Sample 1</h3> 
 </a>
 <a href="https://example.com" class="card-u card-1-u" style="text-decoration: none;">
  <h3>Text Sample 2</h3> 
 </a>
</div>

But the text Text Sample 1 and Text Sample 2 are not vertically centered, but at the top of the Flexbox. It looks like something in my large CSS code is interfering, but I don't know what. My question is assuming we don't know what the rest of the CSS is, can we force this part to do what we want, which is to center the text vertically in the flexbox?

P粉757556355P粉757556355263 days ago885

reply all(1)I'll reply

  • P粉238355860

    P粉2383558602024-04-07 16:46:48

    This happens because .cards-u does not have any height defined. It takes the height of the content as its own height and keeps the content within that area.

    You should use 100vh to give .cards-u the full page height, or do the following:

    .cards-u{
      position: relative;
    }
    
    .card-u{
        position: absolute;
        top: 50%;
        transform: translateY(-50%);
    
    }

    reply
    0
  • Cancelreply