我有一个网格布局。我使用移动优先的方法构建它,这意味着默认情况下(媒体查询之外)所有内容都是针对移动的。
桌面布局如下所示:

我有一个被设置为80em的“主”内容区域。让我们假设这是网站的主页。
但是,如果我需要在某些页面上的“主”区域更窄一点,比如联系人页面,也许是70em而不是80em,但仍然居中,我该怎么办呢?
在网格中,我有以下内容:
.grid-layout {
grid-template-columns:
minmax(0, 1fr)
minmax(0, 80em)
minmax(0, 1fr);
grid-template-rows: repeat(2, auto) 200px 1fr;
}下面是完整的代码,你可以看到它是如何工作的:
:root {
box-sizing: border-box;
}
*,
*::before,
*::after {
box-sizing: inherit;
}
body {
margin: 0;
padding: 0;
}
.grid-layout {
display: grid;
grid-template-columns: 1fr;
grid-template-rows: repeat(2, auto) 1fr 1fr;
min-height: 100vh;
}
.header {
background: lightsalmon;
}
.main {
background: lightseagreen
}
.testimonials {
background: lightgreen;
}
.footer {
align-self: end;
background: lightsalmon;
}
@media (min-width: 52em) {
.grid-layout {
grid-template-columns:
minmax(0, 1fr)
minmax(0, 80em)
minmax(0, 1fr);
grid-template-rows: repeat(2, auto) 200px 1fr;
}
.grid-layout > * {
grid-column: 1/-1;
}
.main {
grid-column: 2;
}
}<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="grid-layout.css">
<title>Grid Layout</title>
</head>
<body>
<div class="grid-layout">
<header class="header">
Header
</header>
<main class="main">
<h2>Main</h2>
<p>Content</p>
<p>Content</p>
<p>Content</p>
<p>Content</p>
<p>Content</p>
</main>
<section class="testimonials">
Testimonials
</section>
<footer class="footer">
Footer
</footer>
</div>
</body>
</html>
基本上布局工作很好,因为它是,我只是想知道如何改变我的主要区域,以不同的宽度在不同的页面。你会使用什么方法?
如有任何建议,欢迎光临。谢谢!
发布于 2021-03-29 23:02:19
一种可能性是定义一个可以在某些特定页面中覆盖的CSS变量,但使用80em作为默认值:
HTML
<div class="grid-layout" style="--w: 70em">
</div>CSS
@media (min-width: 52em) {
.grid-layout {
grid-template-columns:
minmax(0, 1fr)
minmax(0, var(--w, 80em))
minmax(0, 1fr);
grid-template-rows: repeat(2, auto) 200px 1fr;
}
...
}否则,如果您的变体数量有限,则可以创建一组预定义的类,例如
@media (min-width: 52em) {
.grid-layout {
--w : 80em
grid-template-columns:
minmax(0, 1fr)
minmax(0, var(--w))
minmax(0, 1fr);
grid-template-rows: repeat(2, auto) 200px 1fr;
}
...
.grid-layout.variantA { --w: 70em }
.grid-layout.variantB { --w: 90em }
}https://stackoverflow.com/questions/66856523
复制相似问题