css居中小妙招

2020-06-09  本文已影响0人  爱美的程序媛

身为前端,与样式打交道是必不可少的。每次拿到设计小姐姐的设计稿,你就会发现横向、纵向居中是设计小姐姐们的最爱。下面我就来总结一下居中常用的方法吧(喜欢就收藏哦😊)


(1)元素本身居中

a、使用line-height


<div class="box">我是box的文字</div>

.box{

        border: 1px solid #666;

        border-radius: 10px;

        width: 120px;

        height: 30px; 

        line-height: 30px;  /*line-height要和height设置成一样*/

        text-align: center; /*文本内容居中*/

    }

效果如下:

image

b、使用padding居中

.box{

    border: 1px solid #666;

    border-radius: 10px;

    padding: 5px 30px

}

效果如下(简单大方):

image

(2)子元素在父元素居中


<div class="parent">

        <div class="child">我是子元素</div>

    </div>

a、使用position

子元素有宽度和高度时


.parent{

        width: 600px;

        height: 600px;

        border: 1px solid #666;

        margin: 0 auto;

        margin-top: 60px;

        border-radius: 10px;

        position: relative;

    }

    .child{

        background: pink;

        width: 200px;

        height: 200px;

        border-radius: 10px;

        position: absolute;

        left: 50%;

        top: 50%;

        margin-top: -100px;

        margin-left: -100px;

    }

效果如下:

image

子元素无具体宽高时:


.parent{

        width: 600px;

        height: 600px;

        border: 1px solid #666;

        margin: 0 auto;

        margin-top: 60px;

        border-radius: 10px;

        position: relative;

    }

    .child{

        background: pink;

        border-radius: 10px;

        position: absolute;

        left: 50%;

        top: 50%;

        transform: translate(-50%, -50%);

    }

效果如下:

image

b、使用flex居中(好用实力推荐)


.parent{

        width: 600px;

        height: 600px;

        border: 1px solid #666;

        margin: 0 auto;

        margin-top: 60px;

        border-radius: 10px;

        display: flex;

        align-items: center;    /*上下居中*/

        justify-content: center; /* 左右居中*/

    }

    .child{

        background: pink;

        border-radius: 10px;

    }

效果同上哦


有了这些小妙招,再也不怕设计小姐姐的设计稿了😄😄😄。

上一篇 下一篇

猜你喜欢

热点阅读