Home > Blockchain >  Why display table centers item with px but not with vw vh?
Why display table centers item with px but not with vw vh?

Time:10-29

Hi i need to center span inside a div. I tried to center it with display table everything worked when parrent height and wigth were using px unit. But when i switched from px to vh, vw it jumped to the right. I also tried to use text-align: center for div but it did't helped me at all. Does anyone know why it doesnt work with vw vh?

<div
  style={{
   width: '20vw',
   height: '20vh',
   backgroundColor: "black",
   backgroundSize: "100% 100%",
   color: 'white',
   display: 'table'
  }}
>
 <span style={{ fontSize: 30}}>Some text</span>
</div>

enter image description here

CodePudding user response:

Browsers add paddings and margins to elements by default, so maybe you should clear them with:

*{
    padding: 0;
    margin: 0;
    box-sizing: border-box;
}

and may your problem will be fixed, but to center an element i recommend to use flexbox like that:

div{
   width: 20vw;
   height: 20vh;
   background-color: black;
   background-size: 100% 100%;
   color: white;
   display: flex;
   align-items: center;
   justify-content: center;
}

span{
  font-size: 30px;
}
<div>
 <span>text</span>
</div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

You can do this by using

display: table-cell;
text-align: center;
vertical-align: middle;

on span. DEMO

  • Related