CSS佈局之水平居中佈局

概念:水平居中佈局 指的是當前元素在父級元素容器中,水平方向是居中顯示的

方案一: inline-block + text-align

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>水平居中佈局</title>
	<style> #parent { width: 100%; height: 200px; background-color: #ccc; text-align: center; } #child { width: 200px; height: 200px; background: orangered; display: inline-block; } </style>
</head>
<body>
<div id="parent">
	<div id="child"></div>
</div>
</body>
</html>
複製代碼

優缺點

優勢:瀏覽器兼容性好。代碼中使用的均是 CSS 2 中的屬性,瀏覽器兼容性良好。css

缺點text-align 具備繼承性。子元素中的文本會繼承父元素的 text-align 屬性。若子元素中的文本不是居中顯示時,則須要從新設置 text-align 屬性將其覆蓋。html

方案二:table + margin

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>水平居中佈局</title>
<style> #parent { background-color: #ccc; } #child { width: 200px; height: 200px; /* display 的值爲 block 和 table */ display: table; /* margin 屬性:外邊距 * 一個值 - 上右下左 * 二個值 - 第一個值表示上下,第二個值表示左右 * auto 瀏覽器自動計算(等分) * 三個值 - 第一個值表示上,第二個值表示左右,第三個值表示下 * 四個值 - 上右下左 */ margin: 0 auto; background: orangered; } </style>
</head>
<body>
	<!--定位父級元素-->
	<div id="parent">
		<!--定位子級元素-->
		<div id="child"></div>
	</div>
</body>
</html>
複製代碼

優缺點

優勢:只須要對子元素設置就能夠顯示水平居中佈局效果。瀏覽器

缺點:若是子元素脫離文檔流,致使 margin 屬性的值失效。佈局

方案三:absolute + transform

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>水平居中佈局</title>
	<style> #parent { width: 100%; height: 200px; background-color: #ccc; /* 開啓定位 */ position: relative; } #child { width: 200px; height: 200px; background: orangered; /* 當把當前元素設置爲絕對定位後: *若是父級元素沒有開啓定位,當前元素相對於頁面定位, *若是父級元素開啓了定位的話,當前元素相對於父級元素定位 */ position: absolute; left: 50%; /* 子級元素相對於父級元素的左邊 50% */ transform: translateX(-50%); } </style>
</head>
<body>
	<!--定位父級元素-->
	<div id="parent">
		<!--定位子級元素-->
		<div id="child"></div>
	</div>
</body>
</html>
複製代碼

優缺點

優勢:父級元素是否脫離文檔流,不影響子級元素居中顯示效果。ui

缺點transform 屬性是 CSS 3 中新增的屬性,瀏覽器支持狀況很差。spa

相關文章
相關標籤/搜索