Home > Software engineering >  why is CSS align-items not centering my text
why is CSS align-items not centering my text

Time:07-23

.top-part {
    position: relative;
    display: flex;
    background:  rgba(51, 102, 255,0.7);
    width: 100%;
    height: 8cm;
    background-position: center;
    background-size: cover;
}

.not-content {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    text-align: center;
    font-family:'Consolas','Courier New','Trebuchet MS';
    color: white;
    line-height: .5cm;
    flex-wrap: wrap;
}
<section >

        <div >

              <h1><strong>BIG TEXT</strong></h1>
                
              <h4>TEXT</h4>

        </div>
        
</section>

i don't know what error I've made, the "align-items: center;" is not working as it should be, it's not centering my text horizontally

CodePudding user response:

Flexbox is overkill in your case. Just text-align: center; will work fine.

.not-content {
  text-align: center;
}
<div >
  <h3>This is an H3 heading</h3>
  <h4>An H4 heading</h4>
</div>

However, the original issue you're having is due to the flexbox only being as large as the content. This is because your top-part class is display: flex instead of display: block. Below I've highlighted the element in Chrome devtools to illustrate how big your flex content region is; notice how it only fits the text.

display flex only fits content

If you remove the display: flex from the top-part class, it will do what you expect.

CodePudding user response:

give the container <div > a width: 100%; , it will work :

.not-content {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  text-align: center;
  font-family: "Consolas", "Courier New", "Trebuchet MS";
  color: white;
  line-height: 0.5cm;
  flex-wrap: wrap;
  width: 100%;
}
  • Related