css 水平/垂直居中

水平垂直居中

1、定位

.parent{
  position: relative
}
.child{
  position: absolute; 
  left: 50%;
  top: 50%;
  margin: -50px 0 0 -50px; // 已知宽高
// transform: translate(-50%,-50%); // 未知宽高
}

2、flex

      .parent {
        width: 300px;
        height: 300px;

        /* flex布局 */
        display: flex;

        /* 使子项目水平居中 */
        justify-content: center;

        /* 使子项目垂直居中 */
        align-items: center;
      }
      .child {
        width: 100px;
        height: 100px;
      }

    <div class="parent">
      <div class="child"></div>
    </div>

3、table-cell(不推荐)

水平居中

1、marginwidth(已知宽)

div{
  width:1000px;
  margin: 0 auto;
}

2、绝对定位(已知宽)

.ele {
    position: absolute;
    width: 宽度值;
    left: 50%;
    margin-left: -(宽度值/2);
}

3、inline-block(未知宽)
父元素设置:

parent{
  text-align: center;
}
child{
  display: inline-block;
}

4、float + position: relative + left: 50%


image.png

6、Flex

垂直居中

1、绝对定位
水平垂直居中的基础上去掉
margin-left: -xx;

已知自元素宽高
#box {
        width: 300px;
        height: 300px;
        background: #ddd;
        position: relative;
      }
      #child {
        width: 150px;
        height: 100px;
        background: orange;
        position: absolute;
        top: 50%;
        margin-top: -50px;
      }
    
    <div id="box">
      <div id="child"></div>
    </div>



未知子元素宽高
#box {
        width: 300px;
        height: 300px;
        background: #ddd;
        
        position: relative;
      }
      #child {

        background: orange;
        position: absolute;
        top: 50%;
        transform: translate(0, -50%);
      }
    </style>

    <div id="box">
      <div id="child">11</div>
    </div>

2、flex

    #box {
        width: 300px;
        height: 300px;
        background: #ddd;
        
        display: flex;
        /* 垂直居中 */
        align-items: center;  
      }
      #child {
        width: 150px;
        height: 100px;
        background: orange;
      }

    <div id="box">
      <div id="child"></div>
    </div>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容