首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >CSS网格与Breaking布局。如何为不同页面上的内容设置不同的大小?

CSS网格与Breaking布局。如何为不同页面上的内容设置不同的大小?
EN

Stack Overflow用户
提问于 2021-03-29 22:57:38
回答 1查看 29关注 0票数 0

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

桌面布局如下所示:

我有一个被设置为80em的“主”内容区域。让我们假设这是网站的主页。

但是,如果我需要在某些页面上的“主”区域更窄一点,比如联系人页面,也许是70em而不是80em,但仍然居中,我该怎么办呢?

在网格中,我有以下内容:

代码语言:javascript
复制
.grid-layout {
    grid-template-columns:
      minmax(0, 1fr)
      minmax(0, 80em)
      minmax(0, 1fr);
    grid-template-rows: repeat(2, auto) 200px 1fr;
  }

下面是完整的代码,你可以看到它是如何工作的:

代码语言:javascript
复制
: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;
  }
}
代码语言:javascript
复制
<!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>

基本上布局工作很好,因为它是,我只是想知道如何改变我的主要区域,以不同的宽度在不同的页面。你会使用什么方法?

如有任何建议,欢迎光临。谢谢!

EN

回答 1

Stack Overflow用户

发布于 2021-03-29 23:02:19

一种可能性是定义一个可以在某些特定页面中覆盖的CSS变量,但使用80em作为默认值:

HTML

代码语言:javascript
复制
<div class="grid-layout" style="--w: 70em">
</div>

CSS

代码语言:javascript
复制
@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;
  }
  ...
}

否则,如果您的变体数量有限,则可以创建一组预定义的类,例如

代码语言:javascript
复制
@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 }

}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66856523

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档