0

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

j08691
  • 204,283
  • 31
  • 260
  • 272
Vlad
  • 419
  • 1
  • 10
  • 21

2 Answers2

-1

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>
Carlos Guerra
  • 24
  • 1
  • 4
-2

You can do this by using

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

on span. DEMO