日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無先后,達(dá)者為師

網(wǎng)站首頁(yè) 編程語(yǔ)言 正文

讓一個(gè)有寬高的盒子垂直水平居中

作者:bjt_yy 更新時(shí)間: 2022-07-26 編程語(yǔ)言

如何讓一個(gè)有寬高的盒子垂直居中

1.利用盒子寬高和margin

<html>
	<head>
		<style type="text/css">
		*{
			padding: 0;
			margin: 0;
			list-style: none;
		}
		.fu{
			width: 750px;
			height: 600px;
			border: 1px solid gray;
			background-color: antiquewhite;
		}
		.son{
			width: 300px;
			height: 200px;
			border: 1px solid red;
			margin-left: 225px;
			margin-top: 200px;
			background-color: aquamarine;
		}
		</style>
	</head>
	<body>
		<div class="fu">
			<div class="son"></div>
		</div>
	</body>
</html>

該方法是需要精確的父元素寬高的情況下
界面如下圖一:
圖1

2.利用盒子寬高和margin

<html>
	<head>
		<style type="text/css">
		*{
			padding: 0;
			margin: 0;
			list-style: none;
		}
		.fu{
			width: 750px;
			height: 600px;
			border: 1px solid gray;
			background-color: antiquewhite;
		}
		.son{
			width: 300px;
			height: 200px;
			border: 1px solid red;
			margin: 200px auto;
			background-color: aquamarine;
		}
		</style>
	</head>
	<body>
		<div class="fu">
			<div class="son"></div>
		</div>
	</body>
</html>

這種方法相比于第一種是只對(duì)上邊距有明確的控制,而對(duì)左右用auto,與第一種幾乎相同。

3.絕對(duì)定位+translate

<!DOCTYPE html>
<html>
	<head>
		<style type="text/css">
		*{
			padding: 0;
			margin: 0;
			list-style: none;
		}
		.fu{
			width: 750px;
			height: 600px;
			border: 1px solid gray;
			background-color: antiquewhite;
			position: relative;
		}
		.son{
			width: 300px;
			height: 200px;
			border: 1px solid red;
			position: absolute;
			top: 50%;
			left: 50%;
			transform: translate(-50%,-50%);
			background-color: aquamarine;
		}
		</style>
	</head>
	<body>
		<div class="fu">
			<div class="son"></div>
		</div>
	</body>
</html>

結(jié)果同圖一
4.flex布局

<!DOCTYPE html>
<html>
	<head>
		<style type="text/css">
		*{
			padding: 0;
			margin: 0;
			list-style: none;
		}
		.fu{
			width: 750px;
			height: 600px;
			border: 1px solid gray;
			background-color: antiquewhite;
			display: flex;
			justify-content: center;
			align-items: center;
		}
		.son{
			width: 300px;
			height: 200px;
			border: 1px solid red;
			background-color: aquamarine;
		}
		</style>
	</head>
	<body>
		<div class="fu">
			<div class="son"></div>
		</div>
	</body>
</html>

結(jié)果同圖一

這幾總方法都可以用,但是有優(yōu)點(diǎn)也有缺陷,本人一般使用方法2 3多一些。

原文鏈接:https://blog.csdn.net/bjt_yy/article/details/118892887

欄目分類
最近更新