CSS居中之美(一)——垂直居中

CSS实现文本、图片、块级元素等垂直居中的方法

1、使用vertical-align方法,对块级元素进行垂直居中

CSS 的属性 vertical-align 指定了行内水平(inline-level)元素或表格单元格(table-cell)元素的垂直对齐方式.

Html

<div class="wrap">
    <div class="cell">
        <p>hello sublime!</p>
    </div>

CSS

.wrap{
        background-color: grey;
        display: table;     /*父元素首先要声明为table块级表格来显示*/
    }
    .cell{
        display: table-cesll;    /*子元素要以单元格的形式来显示*/
        color: white;
        vertical-align: middle;   /*然后就是利用表格居中属性*/
    }

因为vertical-align使用的对象,所以首先要将父级块元素生命为table(此元素会作为块级表格来显示(类似 table标签 ,表格前后带有换行符。),而将子级块元素生明为table—cell(此元素会作为一个表格单元格显示,类似 td元素和 th元素)。

2、使用line-height实现单行文本的垂直居中

Html

 <div class="parent">
    <div class="child">Text here</div>
 </div>

CSS

.child{
        background-color: grey;
        line-height: 200px;
    }

这里写图片描述

3、使用vertical-align和line-height实现图片的垂直居中

Html

<div class="parent">
    <img src="0.jpg" alt="bikaqqiu">
 </div>

CSS

.parent{
        line-height: 500px;     /*这个很重要*/
        background-color: grey;
        }
img{
    vertical-align: middle;     /*这个也很重要*/
    height: 200px;
    width: 300px;
        }

这里写图片描述

4、绝对定位元素的实现块级元素水平垂直居中

(1)CSS3以前的方法

Html

<div class="parent">
    <div class="child">Text here</div>
 </div>

CSS

.parent {
        position: relative;
        height: 500px;
        width: 500px;
        background-color: grey;
    }
.child {
        position: absolute;
        height: 200px;
        width: 200px;
        top: 50%;
        left: 50%;
        margin-top: -100px;     /*本元素的高度的一半*/
        margin-left: -100px;        /*本元素宽度的一半*/
        background-color: black;
    }

这里写图片描述
我们连水平垂直居中都是实现了,垂直居中还会远吗?
这里秩序我们将left:50%和margin:-100px删除就会得到垂直居中!

(2)CSS3之后的方法

Html文档不变;
CSS

.parent {
        position: relative;
        height: 500px;
        width: 500px;
        background-color: grey;
    }
.child {
        position: absolute;
        height: 200px;
        width: 200px;
        top: 50%;
        left: 50%;
        transform:translate(-50%, 50%); /*这里的50%恰好是一半*/
        background-color: black;
    }

CSS3的兴起,使得有了更好的解决方法,就是使用transform代替margin. transform中translate偏移的百分比值是相对于自身大小的.

5、margin:auto实现块级元素绝对定位元素的水平垂直居中

.wrapper{
        width: 500px;
        height: 500px;
        position: relative;
        background-color: grey;
        }
.cell{
        width: 200px;
        height: 200px;
        position: absolute;
        top: 0;
        bottom: 0;
        left: 0;
        right: 0;
        margin: auto;   /*将外边距设置为auto*/
        background-color: black;
      }

以上就是我收集的是实现元素垂直居中的方法,看你喜欢哪一种了?

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值