CSS position absolute

378 阅读1分钟

上次在写demo时,发现position和自己理解的有点不一致,如果对position topbottom都不设置值时,上下位置还是按正常布局

HTML

<div class="container">
  <div class="bro"></div>
  <div class="btn"></div>
</div>

CSS

.container {
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        width: 100%;
        z-index: 100;
        overflow: hidden;
        background: #f2f3f4;
      }
      .bro{
        position: relative;
        width: 100%;
        height: 75%;
        box-sizing: border-box;
        border: 1px solid black;
      }
      .btn {
        position: absolute;
        left: 0;
        right: 0;
        margin: auto;
        width: 120px;
        height: 40px;
        background: red;
        color: #fff;
        border-radius: 20px;
      }

展示结果如图

image.png 发现想让btn居中,必须同时设置left right margin