css里上下居中怎么弄?

2020-07-23 08:56:32
css里上下居中也就是垂直居中,css中按元素可以分为三种垂直居中方式,分别是单行的行内元素,多行的行内元素以及块元素的垂直居中,下面将做详细介绍。

单行的行内元素

只需要设置单行行内元素的"行高等于盒子的高"即可;

<style>    #father {        width: 500px;        height: 300px;        background-color: skyblue;    }     #son {        background-color: green;        height: 300px;    }</style> <div id="father">    <span id="son">我是单行的行内元素</span></div>

效果:

1556519521438598.jpg

多行的行内元素

使用给父元素设置display:table-cell;和vertical-align: middle;即可;

<style>    #father {        width: 500px;        height: 300px;        background-color: skyblue;        display: table-cell;        vertical-align:middle;    }     #son {        background-color: green;    }</style> <div id="father">

<span id="son">我是多行的行内元素我是多行的行内元素我是多行的行内元素我是多行的行内元素我是多行的行内元素我是多行的行内元素我是多行的行内元素我是多行的行内元素</span>

</div>

效果:

1556519558892168.jpg

块级元素

方案一:使用定位

首先设置父元素为相对定位,再设置子元素为绝对定位,设置子元素的top: 50%,即让子元素的左上角垂直居中;

定高度:设置绝对子元素的 margin-top: -元素高度的一半px; 或者设置transform: translateY(-50%);

<style>    #father {        width: 500px;        height: 300px;        background-color: skyblue;        position: relative;}     #son {        height: 100px;        background-color: green;        position: absolute;        top: 50%;        margin-top: -50px;}</style> <div id="father">    <div id="son">我是块级元素</div></div>

不定高度:利用css3新增属性transform: translateY(-50%);

<style>    #father {        width: 500px;        height: 300px;        background-color: skyblue;        position: relative;}     #son {        width: 100px;        background-color: green;        position: absolute;        left: 50%;        transform: translateY(-50%);}</style> <div id="father">    <div id="son">我是块级元素</div></div>

效果:

1556519576485117.jpg

方案二:使用flexbox布局实现(高度定不定都可以)

使用flexbox布局,只需要给待处理的块状元素的父元素添加属性 display: flex; align-items: center;

<style>    #father {        width: 500px;        height: 300px;        background-color: skyblue;        display: flex;        align-items: center;    }     #son {        width: 100px;        height: 100px;        background-color: green;    }</style> <div id="father">    <div id="son">我是块级元素</div></div>

效果:

1556519592845736.jpg

相关教程:CSS视频教程