我是靠谱客的博主 甜美菠萝,这篇文章主要介绍行内元素和块级元素的居中,现在分享给大家,希望可以做个参考。

1.水平居中:

(1)行内元素:

         对该行内元素的父元素设置text-align:center

(2)块级元素:

         对该块级元素设置margin:0 auto

(3)弹性盒子中的水平居中:

         将某元素定义为弹性盒子:display:flex;

         然后在水平方向居中盒子内的元素:justify-content:center;

2.垂直居中:

(1)行内元素:

         方法一:对该行内元素的父元素设置line-height与height相同:比如父元素div的height为50px,则设置:

复制代码
1
2
3
4
div { height: 50px; inline-height:50px; }

        方法二:设置行内元素vertical-align:middle

(2)块级元素:

     a) 情形一:父元素div设置了宽度:            

复制代码
1
2
3
4
5
6
div{width:100px} div p{ margin:0 auto; height:30px; line-height:30px; }

    b) 情形二:父元素并未设置宽度或者宽度为百分比

           方法一:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#fatherdiv { background-color: #000000; width: 100%; height: 100vh; position: relative; font-family: PingFang SC; } #childdiv { width: 90%; height: 90%; position: absolute; margin: auto; top: 0;left: 0; right: 0; bottom: 0; background-color: #235237; }

方法二:使用transform:

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#fatherdiv { background-color: #000000; width: 100%; height: 100vh; position: relative; font-family: PingFang SC; } #childdiv { width: 90%; height: 90%; position: absolute; top: 50%; left: 50%; transform: translate(-50%,-50%); background-color: #235237; }

(3)弹性盒子中的垂直居中:

         将某元素定义为弹性盒子:display:flex;

         然后在水平方向居中盒子内的元素:align-items:center;



最后

以上就是甜美菠萝最近收集整理的关于行内元素和块级元素的居中的全部内容,更多相关行内元素和块级元素内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(58)

评论列表共有 0 条评论

立即
投稿
返回
顶部