行内元素,块级元素的垂直居中,水平居中

2,640 阅读3分钟

这是我参与11月更文挑战的第5天,活动详情查看:2021最后一次更文挑战

本篇文章针对前端初学者哦

在开发的过程中,我们经常会遇到一些这样或者那样的样式问题,而其中最为常见的就是元素的居中问题。所以,本文就着重来给大家讲一讲,到底如何使我们“不听话的元素”,乖乖的居中了

在处理居中之前,我们要先搞清楚两个概念:

  • 行内元素
  • 块级元素

我们先来看看定义吧:

行内元素:不可以设置宽高、可以和其他的元素共享一行

行内元素:独占一行,可以设置宽高

有了上面的基础,我们就可以判断出,你想要居中的元素,到底是行内元素还是会计元素啦

下面我们来看解决方式吧

一、行内元素

1、行内元素的水平居中:给父级元素使用属性text-align:center

2、行内元素的垂直居中:给父级元素使用属性line-hight:父元素盒子的高度

二、块级元素

1、块级元素的水平居中:给子级元素使用属性margin:0 auto

2、行内元素的水平垂直居中,有四种方法:

介绍之前,先写好我们的html结构,具体的代码如下所示:

<body>
	<div class="outer">
		<div class="inner"></div>
	</div>
</body>

css样式如下:

a、 先把父级元素设置为相对定位
       然后给子元素的top、right、left、bottom设置为0px,还要记得margin设置为auto哦

然后
                .outer{
			width: 500px;
			height: 500px;
			background-color: #ddd;
			border: 1px solid red;
			position: relative;
		}
		.inner{
			width: 100px;
			height: 100px;
			margin:auto; /*这个不要忘了写*/
			position: absolute;
			top: 0px;
			right: 0px;
			bottom: 0px;
			left: 0px;
			background-color: pink;
		}

b、先给父元素设置绝对定位
再给子元素设置决定定位,并且把top设置为父元素宽度的一半再减去子元素本身的宽度,当然left同理。

                .outer{
			width: 500px;
			height: 500px;
			background-color: #ddd;
			border: 1px solid red;
			position: absolute;
		}
		.inner{
			width: 100px;
			height: 100px;
			background-color: pink;
			position: absolute;
			top: calc(50% - 50px);
			left: calc(50% - 50px);
		}

c、先给父元素设置相对定位
再给子元素设置绝对定位,把子元素的top和left设置为父元素宽度的一半,并且将向外的偏移量设置为子元素自己宽高的一半

                .outer{
			width: 500px;
			height: 500px;
			background-color: #ddd;
			border: 1px solid red;
			position: relative;
		}
		.inner{
			width: 100px;
			height: 100px;
			background-color: pink;
			position: absolute;
			left: 50%;
			top: 50%;
			margin-left: -50px;
			margin-top: -50px;
		}

d、这种方式借用的是flex的特性
首先给父元素display设置为flex,然后将justify-content设置为center,align-items也设置为 center。
这里的意思就是让其子元素在自己的主轴和交叉轴上居中
如果不明白的话,可以先去看一看flex布局的一些特性。

                .outer{
			width: 500px;
			height: 500px;
			background-color: #ddd;
			border: 1px solid red;
			display: flex;
			justify-content: center;
			align-items: center;
		}
		.inner{
			width: 100px;
			height: 100px;
			background-color: pink;
			
		}

上面就是本次我要给大家说的内容啦,希望可以解决你们的问题哦,灵活运用就可以啦,我个人在工作中用的比较多的场景是最后一种哦

前端菜鸟一枚,希望大家批评指正,当然也期待大家给予补充哦~