css如何设置垂直居中


本文摘自PHP中文网,作者青灯夜游,侵删。

css设置垂直居中的方法:1、使用line-height属性让文字垂直居中;2、使用CSS3 flex布局让文字垂直居中;3、使用绝对定位和transform让块状元素垂直居中;4、使用flex布局让块状元素垂直居中。

本教程操作环境:windows7系统、CSS3&&HTML5版、Dell G3电脑。

css设置文本文字垂直居中

1、line-height 使文字垂直居中

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>css 垂直居中</title>

<style>

.box{

    width: 300px;

    height: 300px;

    background: paleturquoise;

    line-height:300px;

}

</style>

</head>

<body>

<div class="box">css 垂直居中了--文本文字</div>

</body>

</html>

效果图:

1.png

这样就能让div中的文字水平垂直居中了

2、CSS3的flex布局 使文字垂直居中

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>css 垂直居中</title>

<style>

.box{

   width: 300px;

   height: 200px;

   background: paleturquoise;

   /*设置为伸缩容器*/

   display: -webkit-box;

   display: -moz-box;

   display: -ms-flexbox;

   display: -webkit-flex;

   display: flex;

   /*垂直居中*/

   -webkit-box-align: center;/*旧版本*/

   -moz-box-align: center;/*旧版本*/

   -ms-flex-align: center;/*混合版本*/

   -webkit-align-items: center;/*新版本*/

   align-items: center;/*新版本*/

}

</style>

</head>

<body>

<div class="box">css 垂直居中--文本文字(弹性布局)</div>

</body>

</html>

效果图:

2.png

css设置块状元素垂直居中

1、使用绝对定位和transform(未知元素高度)

如果我们不知道元素的高度,那么就需要先将元素定位到容器的中心位置,然后使用 transform 的 translate 属性,将元素的中心和父容器的中心重合,从而实现垂直居中:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>css 垂直居中</title>

<style>

.box{

width: 300px;

    height: 300px;

    background: #ddd;

    position: relative;

}

.child{

background: #93BC49;

    position: absolute;

    top: 50%;

    transform: translate(0, -50%);

}

</style>

</head>

<body>

<div class="box">

    <div class="child">css 垂直居中,css 垂直居中,css 垂直居中,css 垂直居中,css 垂直居中</div>

</div>

</body>

</html>

效果图:

3.png

2、使用flex布局

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title>css 垂直居中</title>

<style>

.box{

width: 300px;

    height: 300px;

    background: #ddd;

    display: flex;

    flex-direction: column;

    justify-content: center;

}

.child{

width: 300px;

    height: 100px;

    background: #08BC67;

    line-height: 100px;

}

</style>

</head>

<body>

<div class="box">

    <div class="child">css 垂直居中了--弹性布局</div>

</div>

</body>

</html>

效果图:

4.png

(学习视频分享:css视频教程)

以上就是css如何设置垂直居中的详细内容,更多文章请关注木庄网络博客

相关阅读 >>

css怎么设置全屏背景图片

css中的角度单位有哪些?

css网页布局小技巧

css中的长度单位的应用介绍

css如何实现不换行

css border-bottom-style属性怎么用

css动画怎么匀速

css中怎么给按钮添加背景图片(详解及实例)

css中伪类和伪元素有什么区别

css怎么设置文字1行

更多相关阅读请进入《css》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...