banner
LI JIAJUN

LI JIAJUN

# Hello !
github
twitter
zhihu

前端自適應布局方案

流式布局#

使用百分比單位等單位來表示長度和寬度,這樣在整體的長度和寬度變化的時候,裡面的內容也會發生變化。

使用 %#

直接使用百分比,在頁面寬度變化的時候會對應放大縮小。

<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8" />
		<meta name="viewport" content="width=device-width, initial-scale=1.0" />
		<title>Document</title>
	</head>
	<style>
		* {
			margin: 0;
			padding: 0;
			box-sizing: border-box;
		}
		.container-box {
			width: 100%;
			height: 100vh;
			background-color: orange;
			padding: 1px;
		}
		.first,
		.second,
		.third {
			width: 80%;
			height: 30%;
			background-color: skyblue;
			margin: 1% auto;
		}
	</style>

	<body>
		<div class="container-box">
			<div class="first">1</div>
			<div class="second">2</div>
			<div class="third">3</div>
		</div>
	</body>
</html>

使用 rem#

可以根據寬度的變化來修改根標籤html中的 font-size屬性的大小,然後就可以在改變寬度的時候改變頁面中元素的帶下。

<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8" />
		<meta name="viewport" content="width=device-width, initial-scale=1.0" />
		<title>Document</title>
	</head>
	<style>
		.container-box {
			width: 100%;
			height: 100vh;
			padding: 1px;
			background-color: orange;
		}
		.first,
		.second,
		.third {
			width: 20rem;
			height: 20rem;
			margin: 1rem auto;
			background-color: skyblue;
		}
		@media screen and (max-width: 768px) {
			html {
				font-size: 12px;
			}
		}
	</style>

	<body>
		<div class="container-box">
			<div class="first">1</div>
			<div class="second">2</div>
			<div class="third">3</div>
		</div>
	</body>
</html>

直接使用媒體查詢#

這個不就描述了,其實就是和使用 rem 差不多,只不過是直接重寫在不同寬度下的樣式而已。

彈性布局#

display: flex

這個在整個頁面是單個 div 時可能比較有用,如果頁面有多個 div 都需要自適應,那麼可能會相互影響布局。

格網布局#

使用 grid 本身的一些屬性來實現響應式。

<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8" />
		<meta name="viewport" content="width=device-width, initial-scale=1.0" />
		<title>Document</title>
	</head>
	<style>
		.container-box {
			width: 100%;
			height: 100vh;
			padding: 1px;
			display: grid;
			grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); /* 列自適應,最小寬度200px */
			grid-gap: 10px; /* 設置網格間隙為10px */
		}
		.item {
			background-color: #ddd;
			display: flex;
			justify-content: center;
			align-items: center;
			font-size: 24px;
		}
	</style>

	<body>
		<div class="container-box">
			<div class="item">1</div>
			<div class="item">2</div>
			<div class="item">3</div>
			<div class="item">4</div>
			<div class="item">5</div>
			<div class="item">6</div>
		</div>
	</body>
</html>

以上就是常見的幾種 響應式 方案。

載入中......
此文章數據所有權由區塊鏈加密技術和智能合約保障僅歸創作者所有。