水平居中

1 text-align: center(行内元素)
    <div>
        <span>文字内容</span>
    </div>

    父元素
    background-color: cadetblue;
    height: 100px; 
    text-align: center;

    子元素
    background-color: goldenrod; 

图片.png

2 width: fit-content(行内元素)
    <div>
        <span>文字内容</span>
    </div>

    父元素
    background-color: cadetblue;
    height: 100px; 
    width: fit-content; /* 适应子元素的宽度 */
    margin: auto;

    子元素
    background-color: goldenrod; 

图片.png

3 margin:0 auto (块级元素)
    <div>
       <p></p>
    </div>

    父元素
    height: 200px;
    background: coral;
    
    子元素

    width: 100px;
    height: 100px;
    background: cornflowerblue;
    margin:0 auto; 

图片.png

垂直居中

1 单行文本垂直居中 line-height: 父元素高度(行内元素)
    <div>
        <span>文字内容</span>
    </div>

    父元素
    background-color: cadetblue;
    height: 100px;

    子元素
    background-color: goldenrod; 
    line-height: 100px;

图片.png

水平垂直居中

1 定位 + transform
    <div>
       <p></p>
    </div>
    父元素
    height: 200px;
    background: coral; 
    position: relative;

    子元素
    width: 100px;
    height: 100px;
    background: cornflowerblue;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%,-50%);

图片.png

2 定位 + margin:auto
    <div>
       <p></p>
    </div>
    父元素
    height: 200px;
    background: coral; 
    position: relative;

    子元素
    width: 100px;
    height: 100px;
    background: cornflowerblue;
    position: absolute;
    margin: auto;
    left: 0;
    top: 0;
    right: 0;
    bottom: 0

图片.png

3 padding
    <div>
       <p></p>
    </div>

    父元素
    background: coral; 
    padding: 50px;

    子元素
    height: 200px;
    background: cornflowerblue; 

图片.png

4 flex
    <div>
       <p></p>
    </div>

    父元素
    background: green; 
    height: 300px;
    display: flex;
    justify-content: center;
    align-items: center;

    子元素
    height: 100px;
    width: 100px;
    background: gray;

图片.png

5 伪元素
    <div>
       <p></p>
    </div>

    父元素
    background: rgb(100, 178, 197); 
    height: 300px; 
    text-align: center;

    父元素伪类
    height: 100%;
    width: 10px;
    content: "";
    display: inline-block;
    vertical-align: middle;
    background: none;

    子元素
    height: 100px;
    width: 100px;
    background: #f91;
    display: inline-block;
    vertical-align: middle

图片.png

6 calc函数 + padding + background-clip: content-box
    <div>
       <p></p>
    </div>

    父元素
    background: rgb(52, 93, 104); 
    height: 500px; 
    width: 500px


    子元素
    height: 100px;
    width: 100px;
    background: rgb(134, 95, 43);
    padding: calc((100% - 100px) / 2);
    background-clip: content-box;

图片.png


简单即可
6 声望2 粉丝

下一篇 »
vue路由传参