【问题标题】:Fixed position element inheriting width of flex item固定位置元素继承弹性项目的宽度
【发布时间】:2016-03-24 12:19:45
【问题描述】:

我正在构建一个 UI,它需要在视口底部有一个固定位置/粘性元素,其宽度受主要内容区域的限制。主要内容区域的两侧可选地是(兄弟)具有固定宽度的左侧和/或右侧边栏,因此我使用 Flexbox 构建主要内容上带有 flex-grow: 1 的三列​​结构。

我从@Marc Audet 在How can I make a fixed positioned div inherit width of parent? 接受的答案中了解到,在固定元素上设置width: inherit 通常是解决此问题的方法,但它似乎仅在其父元素上有指定宽度时才有效,这考虑到我需要主要内容区域来填充页面的剩余宽度,这对我没有帮助。

有没有人有任何解决这个问题的想法?查看我的Fiddle 以获取代码/示例。任何帮助将不胜感激!

【问题讨论】:

  • 不会为您计算宽度? width: calc(100vw - 150px - 250px);
  • @AntonYakushev 的重点是,如果侧边栏被省略,中间部分会自动增长,否则他可以使用 left:150pxright:250px 代替。
  • @jabram width:inherit 不起作用的原因是width 的默认值是auto,它被继承得很好,在这种情况下它对你没有帮助。我知道您的问题可能的解决方案,但它们非常复杂,涉及多个同级选择器......
  • @NielsKeurentjes 如果有一种简洁的方式来传达这个概念,我很想听听你的建议!
  • '简洁'是我担心的部分 :) 我不久前建立了一个完全一样的设置(遗憾的是对于内部站点,所以无法共享链接)但 CSS 是如此复杂到连我的同事都看不懂呵呵。

标签: css width css-position flexbox fixed


【解决方案1】:

CSS

html {
  box-sizing: border-box;
  font: 400 16px/1.45 'Source Code Pro';
}

*,
*:before,
*:after {
  box-sizing: inherit;
  margin: 0;
  padding: 0;
  border: 0;
  outline: none;
  overflow-x: hidden;
}

body {
  background: #121;
  color: #FEF;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  width: 100vw;
  height: 100vh;
}

.container {
  display: flex;
  color: #fff;
  height: -moz-fit-content;
  height: -webkit-fit-content;
  height: fit-content;
  background: blue;
}

.left {
  background: blue;
  min-height: 100vh;
  min-width: 150px;
  flex-shrink: 0;
}

.middle {
  background: green;
  min-height: 100vh;
  overflow: hidden;
  width: calc(100vw - 400px);
  padding-bottom: 60px;
  flex-grow: 1;
  flex-shrink: 0;
}

.middle .fixed-footer {
  background: orange;
  position: fixed;
  bottom: 0;
  width: 100vw;
  width: inherit;
  padding: 16px 0;
  overflow-x: hidden;
}

.right {
  background: blue;
  min-height: 100vh;
  min-width: 250px;
  flex-shrink: 0;
}

@media screen and (min-width: 640px) {
  html {
    margin-left: calc(100vw - 100%);
    margin-right: 0;
    overflow-y: auto;
  }
}

添加了星球大战 ipsum 内容以展示 .middle 的垂直灵活性以及 .fixed-footer 如何是静止的并且是 .middle 的宽度。

DEMO

【讨论】:

  • 有趣的解决方案,谢谢!我会尝试一下,但对我来说不利的是溢出:滚动,它将始终在 PC 上显示一个滚动条,我正试图摆脱它。
  • 如果它没有滚动条,您将如何访问延伸到固定页脚下方的内容?如果您使用auto,它会跳过滚动条的宽度,从而产生难看的偏移。
  • 我宁愿滚动页面而不是元素本身。如果左右侧边栏也有很多内容,那么我们将处理三个独立滚动的列。
  • 我想我可以适应这种情况并让滚动条出现和消失而不会发生跳跃。
  • @jabram 检查更新,我想我做了我认为不可能的事情。
猜你喜欢
  • 1970-01-01
  • 2022-08-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-26
  • 1970-01-01
  • 2016-03-13
相关资源
最近更新 更多