修复了 div 故意丢失数据的容器

Fixed div container with intentional data loss

如何在页面上创建一个固定的 div 容器,以便当页面宽度缩小时,容器内的元素保持静态并且只是从页面的左侧和右侧溢出?我还需要容器在没有任何水平滚动的情况下保持在页面中心。

大宽度:

更小的宽度:

我尝试使用 white-space: nowrap; overflow-x: hidden,但这对我不起作用。在上面的示例中,有 7 个不同的框(假设这些是 7 个不同的图像),我可以重复这些以防屏幕宽度变得非常宽。

这可能是您想要实现 X 要求 Y 而 Z 可能是更好的选择的问题类型。

我完全不确定您为什么要使用固定定位,这意味着图像描述的不是定位,而是元素的流动。

无论如何,如果我正确理解你想要什么,你可以使用 flexBox 做到这一点,


.centered_content {
  display: flex;
  justify-content: center;
}

尝试使用它。这不是你要找的吗?然而,这取决于知道容器块的总宽度 - 您可以在使用 js 加载页面时计算它(或通过 jQuery 更简单)。

所以.static-container必须是.block-items宽度(包括边距),并且.static-container的css属性"left"必须是其宽度的一半宽度。

抱歉,如果它不适合您,请立即手写这个简短的想法:)

至于自动重复 - 嗯,看来您需要实时检查屏幕宽度,复制 DOM 中的项目并在屏幕宽度变化时重新计算 .static-container。我假设你的项目不是背景,可以重复x...

<!doctype html>
<html>
<body>
<style type='text/css'>
.main-container { position:relative;width:100%;height:100px;background:red;overflow:hidden }
.static-container { position:absolute;width:700px;margin-left:50%;left:-350px;height:80px;background:green; }
.block-items { float:left;margin:5px;width:60px;height:60px;background:orange; }
</style>

<div class='main-container'>
    <div class='static-container'>
        <div class='block-items'>1</div>
        <div class='block-items'>2</div>
        <div class='block-items'>3</div>
        <div class='block-items'>4</div>
        <div class='block-items'>5</div>
        <div class='block-items'>6</div>
        <div class='block-items'>7</div>
        <div class='block-items'>8</div>
        <div class='block-items'>9</div>
        <div class='block-items'>10</div>
    </div>
</div>


</body>
</html>

假设您的目标浏览器支持 flexbox, CSS3 selectors and @media,那么您使用 @media 规则来定义 width 开始和结束元素应该​​应用 display: none .

使用 display: flexjustify-content: space-around; 使子项 spaced 在页面上均匀分布。 flex-growflex-shrinkflex-basis 的默认值允许子项缩小(如您的图片所示)但不会增长 - 增长的是 space。最后,随着页面变窄,margin 在子项之间保留一些 space。

解决方案也作为 jsFiddle,因为输出窗格更容易拖动以折叠宽度并查看所需的输出

更新: 解决了通过指定没有 flex-grow 和固定的 flex-basis: 100pxflex: 0 0 100px 来固定 width/height 子项的评论 -另见 updated jsFiddle

section {
  display: flex;
  flex-direction: row;
  justify-content: space-around;
}

.box {
  width: 100px;
  max-width: 100px;
  height: 100px;
  max-height: 100px;
  border: 1px dashed red;
  margin: 0 10px;
  flex: 0 0 100px;
}

@media (max-width: 820px) {
  .box:first-child,
  .box:last-child {
    display: none;
  }
}

@media (max-width: 620px) {
  .box:nth-child(2),
  .box:nth-last-child(2) {
    display: none;
  }
}

@media (max-width: 420px) {
  .box:nth-child(3),
  .box:nth-last-child(3) {
    display: none;
  }
}
<section>
  <div class="box">1</div>
  <div class="box">2</div>
  <div class="box">3</div>
  <div class="box">4</div>
  <div class="box">5</div>
  <div class="box">6</div>
  <div class="box">7</div>
</section>