【问题标题】:Why display table centers item with px but not with vw vh?为什么用 px 而不用 vw vh 显示表格中心项目?
【发布时间】:2021-12-14 00:30:36
【问题描述】:

您好,我需要在 div 中居中跨度。 我试图将它与显示表居中,当父高度和 wigth 使用 px 单位时,一切正常。但是当我从 px 切换到 vh 时,vw 它跳到了右边。 我也尝试使用 text-align: center for div 但它根本没有帮助我。 有谁知道为什么它不适用于 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>

【问题讨论】:

  • 为您的 div 添加边框以注意您在小屏幕上可能面临的溢出

标签: html css jsx js-xlsx


【解决方案1】:

你可以使用

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

在跨度上。 DEMO

【讨论】:

    【解决方案2】:

    浏览器默认为元素添加填充和边距,所以也许你应该清除它们:

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

    也许你的问题会得到解决,但是为了使元素居中,我建议使用这样的 flexbox:

    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>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-09-11
      • 1970-01-01
      • 1970-01-01
      • 2015-02-19
      • 2010-10-11
      • 1970-01-01
      • 2019-11-18
      相关资源
      最近更新 更多