我正在尝试使用 overflow-x:scroll &创建一个带有(平铺)背景图像的水平滚动窗格。 white-space:nowrap 。该窗格跨越任意数量的元素。
CSS:
.frame {
overflow-x: scroll;
}
.pane {
background-image: url(free-tile-floor-texture.jpg);
background-repeat: repeat;
white-space: nowrap;
}
.item {
display: inline-block;
width: 150px;
height: 50px;
background-color: grey;
}
HTML:
<div class="frame">
<div class="pane">
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
</div>
</div>
我希望背景图块自动跨越窗格的整个宽度,包括其所有项目元素。目前它只填充框架宽度。罪魁祸首似乎是窗格宽度属性 - 它不会调整窗格内容的总宽度。
Ofc,它通过手动调整width属性来工作,但我需要它动态调整。
如何让窗格的背景图像填满窗格的全宽?还有另一种方法可以达到同样的效果吗?
答案 0 :(得分:15)
将此行添加到.pane
display: inline-block;
答案 1 :(得分:3)
block
元素(例如<div>
)默认采用其父级的宽度(如果未设置width
),并且不会进一步扩展(即使子级内容溢出)。
inline
元素(例如<span>
)不是这种情况,它将采用子内容的宽度。
因此,通过使用inline-block
,您将受益于子内容的宽度和高度,并拥有所需的内容。
(存在其他解决方案,例如:float: left;
,position: absolute;
,...)
我遇到了同样的问题,我想创建一个旋转木马(或OP要求的带有平铺的水平滚动窗格),并在其末尾添加填充,因此最后一个项目不会折叠到视口的边缘
因此,基本上,您将使carrousel元素可滚动(frame
),然后是一个容器,用于放置带有填充的图块(pane
),最后是图块({{1} } s:
item
body {
margin: 20px;
}
.frame {
overflow-x: scroll;
}
.pane {
background-color: grey;
padding: 20px;
white-space: nowrap
}
.item {
background-color: red;
display: inline-block;
width: 100px;
height: 100px;
margin-right: 20px;
}
.item:last-child {
margin-right: 0;
}
如您所见,填充在开头而不是结尾工作,因为<div class="frame">
<div class="pane">
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
</div>
</div>
的宽度不会扩展到父宽度(在此pane
的宽度情况)。
在frame
上添加display: inline-block;
可以解决此问题:
pane
body {
margin: 20px;
}
.frame {
overflow-x: scroll;
}
.pane {
background-color: grey;
display: inline-block;
padding: 20px;
white-space: nowrap
}
.item {
background-color: red;
display: inline-block;
width: 100px;
height: 100px;
margin-right: 20px;
}
.item:last-child {
margin-right: 0;
}
<div class="frame">
<div class="pane">
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
</div>
</div>
):与OP中关于white-space: nowrap;
规则的问题有所不同,如果您正在寻找一种更现代的解决方案来创建轮播,则可以使用white-space: nowrap;
规则来实现,例如flex容器默认情况下不会自动换行,这也会使CSS更加整洁:
flex
body {
margin: 20px;
}
.frame {
overflow-x: scroll;
}
.pane {
background-color: grey;
display: inline-flex;
padding: 20px;
}
.item {
background-color: red;
width: 100px;
height: 100px;
margin-right: 20px;
}
.item:last-child {
margin-right: 0;
}
答案 2 :(得分:0)
您可以在框架中定义背景图像,这是整个面板
http://jsfiddle.net/erenyener/9u29k/6/
.frame {
overflow-x: scroll;
background-image: url(http://store.got3d.com/products/30-tile-floor-textures/thumbnails/free-tile-floor-texture.jpg);
background-repeat: repeat;
}