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>

以上就是常见的几种 响应式 方案。

加载中...
此文章数据所有权由区块链加密技术和智能合约保障仅归创作者所有。