css水平垂直居中

2020-03-31  本文已影响0人  Zhou_qn

参考文章: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>

居中元素定宽高

<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>

居中元素未知宽高

<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>
<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>
 <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>
上一篇下一篇

猜你喜欢

热点阅读