css水平垂直居中

参考文章:https://yanhaijing.com/css/2018/01/17/horizontal-vertical-center/

作者写的很详细
自己记录几个以后用

  • 居中元素定宽高
  1. absolute+负margin
  2. absolute+margin auto
  3. absolute+calc函数
  • 居中元素未知宽高
  1. absolute+transform
  2. css-table
  3. flex

有父元素和子元素

<div class="wp">
    <div class="box size">1212</div>
</div>

居中元素定宽高

  • absolute+负margin
  • absolute+margin auto
  • absolute+calc函数
    由于absolute他是基于父元素左上角的位置定位,所以会超过中间,因此配合一些方法进行调整
<style>
        /*定宽高*/
        .wp {
            position: relative;
            border: 1px solid red;
            width: 300px;
            height: 300px;
        }
        .box {
            position: absolute;
            background: green;

            /*1.absolute+负margin*/
            top: 50%;
            left:50%;
            margin-left: -50px;
            margin-top: -50px;

            /*2.absolute+margin auto*/
            top:0;
            bottom: 0;
            left: 0;
            right: 0;
            margin: auto;

            /*3.absolute+calc函数*/
            top: calc(50% - 50px);
            left: calc(50% - 50px);

        }

        .box.size{
            width: 100px;
            height: 100px;
        }

    </style>

居中元素未知宽高

  • absolute+transform
<style>
        .wp {
            position: relative;
            border: 1px solid red;
            width: 300px;
            height: 300px;
        }
        .box {
            position: absolute;
            background: green;
            top:50%;
            left:50%;
            transform: translate(-50%,-50%);
        }
        .box.size{
            width: 100px;
            height: 100px;
        }

    </style>
  • css-table
<style>
        .wp {
            border: 1px solid red;
            width: 300px;
            height: 300px;
            display: table-cell; /*此元素会作为一个表格单元格显示(类似 <td> 和 <th>)*/
            text-align: center;
            vertical-align: middle;
        }
        .box {
            background: green;
            display: inline-block; /*行内块元素*/
        }
        .box.size{
            width: 100px;
            height: 100px;
        }
    </style>
  • flex
 <style> 
        .wp {
            border: 1px solid red;
            width: 300px;
            height: 300px;
            display: flex;  /* flex布局 */
            justify-content: center;   /* 定义项目在主轴上的对齐方式。*/
            align-items: center;  /*定义在交叉轴上的对齐方式*/
        }
        .box {
            background: green;
        }
        .box.size{
            width: 100px;
            height: 100px;
        }
        
    </style>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容