【问题标题】:How to use margin to center elements without erasing the older value of margin top and left?如何使用边距使元素居中而不删除边距顶部和左侧的旧值?
【发布时间】:2019-01-24 22:08:23
【问题描述】:

有什么方法可以使用自动边距使元素居中而不删除边距顶部和底部的旧值?请注意它们是未知的。

我尝试将左右边距设为自动,它起作用了,但我想知道是否有任何方法可以在一行中做到这一点,你可以写一些东西而不是 0 来保留旧值

<style>
  .test {
    display: block;
    margin-left: auto;
    margin-right: auto;
    background-color: grey;
    width: 200px;
  }
</style>
<div class="test">this is test div</div>

它在这里确实有效,但是有什么方法可以通过在边距顶部和底部写入一个值来使用边距来保持旧值而不知道它?

【问题讨论】:

  • 不,唯一的方法是你已经完成的那个

标签: html css


【解决方案1】:

创建另一个 div 并将您的代码放入其中。请检查以下内容: 我已删除边距 css。

  .test {
    display: inline-block;
    background-color: grey;
    width: 200px;
  }
<div style="text-align: center;">
<div class="test">this is test div</div>
</div>

【讨论】:

    【解决方案2】:

    你可以试试这个

          <style>
            .parent {
                display: flex;
              justify-content: center;
            }
            .test {
              background-color: grey;
              width: 200px;
            }
          </style>
    
        <div class="parent">
           <div class="test">this is test div</div>
        </div>
    

    【讨论】:

      【解决方案3】:

      答案是否定的,你不能那样做。您正在使用唯一正确的方法。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-10-25
        • 1970-01-01
        • 2012-07-22
        • 2019-08-06
        • 1970-01-01
        • 2017-10-06
        相关资源
        最近更新 更多