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

學無先后,達者為師

網站首頁 編程語言 正文

讓一個有寬高的盒子垂直水平居中

作者:bjt_yy 更新時間: 2022-07-26 編程語言

如何讓一個有寬高的盒子垂直居中

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>

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

3.絕對定位+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>

結果同圖一
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>

結果同圖一

這幾總方法都可以用,但是有優點也有缺陷,本人一般使用方法2 3多一些。

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

欄目分類
最近更新