首页 > 解决方案 > 如何使用边距使元素居中而不删除边距顶部和左侧的旧值?

问题描述

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

我试图使左右边距自动并且它起作用了,但我想知道是否有任何方法可以在一行中做到这一点,你可以写一些东西而不是 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>

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

标签: htmlcss

解决方案


你可以试试这个

      <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>

推荐阅读