水平垂直剧中的方法?

176 阅读1分钟

DOM结构及css:

    <div class="outerbox">
      <div class="innerbox"></div>
    </div>
    .outerbox {
        width: 100%;
        height: 500px;
        background-color: antiquewhite;
      }

      .innerbox {
        width: 200px;
        height: 200px;
        background-color: aqua;
      }

效果展示:

image.png

  1. 方法一:父元素使用相对定位,子元素设置position:absolate; left:50%;top50%;trasnform:translate(-50%,-50%);
    .outerbox {
        width: 100%;
        height: 500px;
        background-color: antiquewhite;
        position: relative;
      }

      .innerbox {
        width: 200px;
        height: 200px;
        background-color: aqua;
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
      }

效果展示:

image.png

  1. 方法二:父元素相对定位,子元素设置:position:absolute;left:50%;top:50%;margin-left:100px;margin-top:-100px;
    .outerbox {
        width: 100%;
        height: 500px;
        background-color: antiquewhite;
        position: relative;
      }

      .innerbox {
        width: 200px;
        height: 200px;
        background-color: aqua;
        position: absolute;
        top: 50%;
        left: 50%;
        margin-left: -100px;
        margin-top: -100px;
      }

效果展示:

image.png

  1. 方法三:父元素使用flex布局,设置样式为:display:flex;algin-items:center;justify-content: center;
    .outerbox {
        width: 100%;
        height: 500px;
        background-color: antiquewhite;
        display: flex;
        align-items: center;
        justify-content: center;
      }

      .innerbox {
        width: 200px;
        height: 200px;
        background-color: aqua;
      }

效果展示:

image.png

  1. 父元素使用相对定位,子元素设置:position:absolute;left:0;top:0;bottom:0;right:0;margin:auto;
    .outerbox {
        width: 100%;
        height: 500px;
        background-color: antiquewhite;
        position: relative;
      }

      .innerbox {
        width: 200px;
        height: 200px;
        background-color: aqua;
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        margin: auto;
      }

效果展示:

image.png

  1. 使用grid布局
    .outerbox {
        width: 100%;
        height: 500px;
        background-color: antiquewhite;
        display: grid;
      }

      .innerbox {
        width: 200px;
        height: 200px;
        background-color: aqua;
        margin: auto;
      }

效果展示:

image.png