首页 > 解决方案 > 全角元素破坏了使用 display: grid 创建的布局

问题描述

我有一个简单的布局,我使用由主元素和侧边栏组成的 CSS 网格创建(请参阅片段)。在侧边栏内,我有一个子元素,我想在移动设备上全角(即忽略布局容器周围的填充)。

.full-width元素确实是全角的,但显然发生的事情是它使整个网格成为100vw,这使得mainaside溢出.container(灰色元素)。我怎样才能让它保持全宽并保持mainaside的范围内.container?另一个要求是全角元素保留在文档流中(因此没有固定或绝对定位)。

.page {
    background: pink; 
    padding: 30px; 
}

.container {
    display: grid; 
    grid-template-areas: "aside" "main"; 
    background: grey; 
    padding: 60px 0;
}

aside {
    background: yellow;
}

main {
    background: green; 
}

.full-width {
    width: 100vw; 
    margin-left: -30px;
    background: red;
}
<div class="page">
<div class="container">
    <main>
        <p>I'm the main content</p>
    </main>
    <aside>
        <p>I'm the sidebar</p>
        <div class="full-width">
            <p>I'm the full width element</p>
        </div>
    </aside>
</div>
</div>

标签: csscss-grid

解决方案


第一个也是简单的解决方案是将列设置100%为避免溢出:

.page {
  background: pink;
  padding: 30px;
}

.container {
  display: grid;
  grid-template-areas: "aside" "main";
  grid-template-columns: 100%;
  background: grey;
  padding: 60px 0;
}

aside {
  background: yellow;
}

main {
  background: green;
}

.full-width {
  width: 100vw;
  margin-left: -30px;
  background: red;
}

body {
 margin:0;
}
<div class="page">
  <div class="container">
    <main>
      <p>I'm the main content</p>
    </main>
    <aside>
      <p>I'm the sidebar</p>
      <div class="full-width">
        <p>I'm the full width element</p>
      </div>
    </aside>
  </div>
</div>

或者简单地在两边使用负边距来获得你想要的全宽:

.page {
  background: pink;
  padding: 30px;
}

.container {
  display: grid;
  grid-template-areas: "aside" "main";
  background: grey;
  padding: 60px 0;
}

aside {
  background: yellow;
}

main {
  background: green;
}

.full-width {
  margin-left: -30px;
  margin-right: -30px;
  background: red;
}
body {
 margin:0;
}
<div class="page">
  <div class="container">
    <main>
      <p>I'm the main content</p>
    </main>
    <aside>
      <p>I'm the sidebar</p>
      <div class="full-width">
        <p>I'm the full width element</p>
      </div>
    </aside>
  </div>
</div>


推荐阅读