元素水平垂直居中和两栏布局

63 阅读1分钟
  1. 使用position + transform
<div class="wrap">
    <div class="box"></div>
</div>
<style>
    .wrap {
        width: 300px;
        height: 300px;
        border: 1px solid red;
        position: relative;
    }
    .box {
        height: 100px;
        width: 100px;
        border: 1px solid blue;
        position: absolute;
        left: 50%;
        right: 50%;
        transform: translate3d(-50%, -50%, 0)
    }
</style>
  1. 使用flex
//html 
......
<style>
    .wrap {
        width: 300px;
        height: 300px;
        border: 1px solid red;
        display: flex;
        justify-content: center;
        align-item: center;
    }
    .box {
        height: 100px;
        width: 100px;
        border: 1px solid blue;
    }
</style>
  1. 两栏布局(左侧固定宽度右侧自适应)
  • 左侧float: left,右侧margin-left
  • 左侧float: left,右侧overflow: hidden(通过overflow清除浮动)
  • 直接利用定位
  • 利用弹性布局
.warp { display: flex }
.left { width: 200px }
.right { flex: 1 }