【问题标题】:CSS Grid content-area horizontally expansion for filling the containerCSS Grid 内容区域水平扩展,用于填充容器
【发布时间】:2020-11-25 08:19:57
【问题描述】:

我有一个 CSS Grid 容器,里面有一个侧边栏和内容区域。我想当用户关闭侧边栏时,内容区域水平扩展以填充容器的整个宽度。 在下面的示例中,我使用 transformX(-100%) 悬停侧边栏进行隐藏,使用 transformX(0%) 显示鼠标侧边栏:

.test-container {
  display: grid;
  background-color: aquamarine;
  grid-template-columns: 1fr 2fr;
  grid-template-areas: "sidebar content";
  height: 100vh;
}

.test-sidebar {
  background-color: blue;
  grid-area: sidebar;
  transform: translateX(0%);
  font-size: 40px;
  color: white;
  text-align: center;
  transition: 2000ms;
}

.test-sidebar:hover {
  transform: translateX(-100%);
  transition: 2000ms;
}

.test-content {
  background-color: blueviolet;
  font-size: 40px;
  text-align: center;
  grid-area: content;
  color: white;
}
<div class="test-container">
  <div class="test-sidebar">Sidebar</div>
  <div class="test-content">Content</div>
</div>

【问题讨论】:

  • 我们可以使用Js吗?
  • 如果可能的话,我更喜欢使用纯 CSS 解决方案。

标签: css css-grid css-transforms expand


【解决方案1】:

这是一个悬停在所有网格元素上的解决方案,只是为了演示我们如何处理两个不同的单元格。这里我们在.test-container 中有grid-template-columns: auto 1fr;,在.test-sidebar 中有静态宽度。现在它们正在按照您的意愿展开/折叠。

关于其他行为,“当用户关闭侧边栏时”是什么意思?请描述这个动作。描述侧边栏的两种行为,在这种情况下它应该折叠和展开?我认为,整个解决方案将需要 JS。如果需要,我会在您的描述后添加。

.test-container {
  display: grid;
  background-color: aquamarine;
  grid-template-columns: auto 1fr;
  height: 100vh;
  transition: all 2s ease;
}

.test-sidebar {
  background-color: blue;
  font-size: 40px;
  color: white;
  text-align: center;
  overflow: hidden;
  width: 200px;
  transition: all 2s ease;
}

.test-container:hover .test-sidebar {
  width: 0;
}

.test-content {
  background-color: blueviolet;
  font-size: 40px;
  text-align: center;
  color: white;
}
<div class="test-container">
  <div class="test-sidebar">Sidebar</div>
  <div class="test-content">Content</div>
</div>

【讨论】:

  • 非常感谢。我认为这是一个了不起的解决方案,除了用于滑入和滑出的动画,侧边栏。
  • 您可以通过将transition: all 2s ease; 更改为.test-container.test-sidebar 来调节动画。如果我能以某种方式改进此代码 - 请告诉我想要的结果。
  • 如果我从您的样式中删除侧边栏的宽度并添加 margin-left: -200px;在 .test-container:hover .test-sidebar 部分中,动画将变成我想要的,但我认为从技术上讲使用负边距并不是一个好主意。
  • 负边距绝对没问题,在很多解决方案中都有使用。在 Bootstrap 4 网格中,您可以在每个 .row 中看到负边距
  • 为了关闭侧边栏,我使用 JavaScript。这里我只是使用悬停来简化我的示例。
猜你喜欢
  • 1970-01-01
  • 2014-10-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多