CSS如何设置div居中显示?附两种方法!

2021-05-11 14:00:46 浏览数 (6957)

我们在开发网页时,有时候需要设定 div 居页面中间显示,这个功能如何实现呢?那么这篇文章告诉你 CSS 如何设置 div 居中显示。

方法一

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>设置div放置在页面中央- 编程狮(w3cschool.cn)</title>
	<style type="text/css">
		*{
			margin: 0;
			padding: 0;
		}
		div{
			width: 100px;
			height: 100px;
			position: absolute;
			top: 50%;
			left: 50%;
			background-color: red;
		}
	</style>
</head>
<body>
	<div></div>
</body>
</html>

此方法中,如果没有设置 transform 属性,那么整个 div 将以左上点的位置居中于整个页面中央。设置 transform 后,中点的位置变为 div 的中心点。具体实现效果如下:

设置div放置在页面中央

方法二


div{
			background-color: black;
			height: 50%;
			width: 50%;
			position: fixed;
			top: 0;
			right: 0;
			bottom: 0;
			left: 0;
			margin: auto;
		}

此方法通过设定 div 的定位为固定定位,然后分别设置上下左右。进而使得整个 div 居中显示。具体效果如下:

设置div放置在页面中央

以上就是文章“ CSS 如何设置 div 居中显示?附两种方法!”的全部内容。更多 CSS 学习请关注 w3cschool 官网。