php垂直居中,css中有哪些方法可以实现垂直居中

本文详细介绍了使用CSS实现元素垂直居中的五种常见方法:1) 利用line-height;2) 父容器相对定位和子元素绝对定位结合margin;3) 弹性布局flex;4) 通过transform位移;5) 网格布局。这些方法适用于不同场景,帮助开发者灵活应对各种布局需求。
摘要由CSDN通过智能技术生成

11ac8819681716debcff59c0e9ea8b06.png

css实现垂直居中的方法如下:

1、利用line-height实现居中,这种方法适合纯文字类的;

.parents {

height: 400px;

line-height: 400px;

width: 400px;

border: 1px solid red;

text-align: center;

}

.child {

background-color: blue;

color: #fff;

}

css布局,实现垂直居中

效果:

39d84188d0ec18506f6f0fa2f79a4955.png

(推荐教程:CSS教程)

2、通过设置父容器相对定位,子级设置绝对定位,标签通过margin实现自适应居中;

.parents {

height: 400px;

width: 400px;

border: 1px solid red;

position: relative;

}

.child {

width: 200px;

height: 100px;

line-height: 100px;

text-align: center;

color: #fff;

background-color: blue;

/* 四个方向设置为0, 然后通过margin为auto自适应居中 */

position: absolute;

top: 0;

right: 0;

bottom: 0;

left: 0;

margin: auto;

}

css布局,实现垂直居中

效果:

39c440fa1c1684b987687385e0ab5579.png

3、弹性布局flex 父级设置display: flex; 子级设置margin为auto实现自适应居中;

.parents {

height: 400px;

width: 400px;

border: 1px solid red;

display: flex;

}

.child {

width: 200px;

height: 100px;

line-height: 100px;

text-align: center;

color: #333;

background-color: yellow;

margin: auto;

}

css布局,实现垂直居中

效果:

f5aab1430cd6c36ba0733ee94aed1052.png

4、父级设置相对定位,子级设置绝对定位,并且通过位移transform实现;

.parents {

height: 400px;

width: 400px;

border: 1px solid red;

position: relative;

}

.child {

width: 200px;

height: 100px;

line-height: 100px;

text-align: center;

color: #fff;

background-color: green;

position: absolute;

top: 50%;

left: 50%;

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

}

css布局,实现垂直居中

效果:

40404e4a09f98c6d8e631efe47d496b9.png

5、父级设置弹性盒子,并设置弹性盒子相关属性;

.parents {

height: 400px;

width: 400px;

border: 1px solid red;

display: flex;

justify-content: center; /* 水平 */

align-items: center; /* 垂直 */

}

.child {

width: 200px;

height: 100px;

color: black;

background-color: orange;

}

效果:

b56e4c97f6ea2fe2b9e4d6806ecee3f1.png

6、网格布局,父级通过转换成表格形式,然后子级设置行内或行内块实现。(需要注意的是:vertical-align: middle使用的前提条件是内联元素以及display值为table-cell的元素)。

效果:

ed591a72b7360dd0005d8dfd64449d9a.png

.parents {

height: 400px;

width: 400px;

border: 1px solid red;

display: table-cell;

text-align: center;

vertical-align: middle;

}

.child {

width: 200px;

height: 100px;

color: #fff;

background-color: blue;

display: inline-block; /* 子元素设置行内或行内块 */

}

相关视频教程推荐:css视频教程

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值