前端自适应布局方案

前端自适应布局方案

流式布局

使用百分比单位等单位来表示长度和宽度,这样在整体的长度和宽度变化的时候,里面的内容也会发生变化。

使用 %

直接使用百分比,在页面宽度变化的时候会对应放大缩小。

<!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>

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

  • 25
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

城南顾北

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值