全角元素打破了使用display:grid创建的布局

问题描述 投票:0回答:1

我有一个简单的布局,我用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>
css css-grid
1个回答
2
投票

首先,简单的解决方案是将列设置为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>
© www.soinside.com 2019 - 2024. All rights reserved.