我有网格布局。我使用mobile-first方法构建它,这意味着默认情况下(媒体查询之外)所有内容都是针对Mobile的。
桌面布局如下所示:
我有一个“主”内容区域,它被设置为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;
}
下面是完整的代码,您可以看到它的工作原理:
null
: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>
null
基本上,布局工作很好,因为它是,我只是想知道,我如何可以改变的主要区域,以不同的宽度,在不同的页面。你会用什么方法?
欢迎任何建议。谢谢!
一种可能是定义一个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 }
}