[英]Resize position absolute element width to content with CSS
I'm trying to put elements in a horizontal row so I can scroll through them, for this I have made an inner and an outer container. 我试图将元素放在水平行中,以便可以滚动它们,为此,我制作了一个内部容器和一个外部容器。 The outer container has a fixed width and the inner container should have a width that is determined by it's content which can be larger than the outer div.
外部容器的宽度是固定的,内部容器的宽度应由其内容决定,该宽度可以大于外部div。
HTML 的HTML
<div id="outer">
<div id="inner">
<ul>
<li class="item"></li>
<li class="item"></li>
<li class="item"></li>
<li class="item"></li>
<li class="item"></li>
</ul>
</div>
</div>
CSS 的CSS
#outer{
width:250px;
position: relative; /* required to make overflow hidden work */
overflow:hidden; /* commented to demonstrate the issue */
background-color: lightgreen;
height: 80px;
}
#inner {
position: absolute;
width: 1000px; /* <- needs to scale to content */
}
ul {
margin: 0;
padding: 0;
}
.item:first-child{
margin-left:0;
}
.item {
width: 100px;
height: 80px;
background-color: lightblue;
margin-left: 10px;
display:inline-block;
}
I'm trying to solve this issue using CSS alone but I've been unsuccesful so far. 我正尝试仅使用CSS来解决此问题,但到目前为止我一直没有成功。 For this issue, browser compatibility is a non-issue.
对于此问题,浏览器兼容性不是问题。
What I have 我有的
What I want 我想要的是
Use white-space: nowrap;
使用
white-space: nowrap;
on #inner
在
#inner
i dont't know if i get your question right, but have you tried it with 我不知道我是否正确回答了您的问题,但是您是否尝试过
overflow-x: scroll;
overflow-y: hidden;
Just make some few modifications 只需进行一些修改
#inner{width: 750px;}
#outer{width: 250px;overflow-x: auto;}
You HTML is invalid as divs cannot be children of a ul
. 您的HTML无效,因为div不能是
ul
。
In fact, I'm not sure you need the ul
at all as you can achieve what you are after without it. 实际上,我不确定您是否完全需要
ul
,因为没有它就可以实现您所追求的目标。
I have widened the outer div in the Fiddle so you can see what is going on 我在小提琴中加宽了外部div,以便您了解发生了什么情况
#outer { width: 250px; position: relative; overflow: hidden; background-color: lightgreen; height: 80px; margin: auto; text-align: center; } #inner { white-space: nowrap; display: inline-block; background: red; } .item:first-child { margin-left: 0; } .item { width: 100px; height: 80px; background-color: lightblue; margin-left: 10px; display: inline-block; }
<div id="outer"> <div id="inner"> <div class="item"></div> <div class="item"></div> <div class="item"></div> <div class="item"></div> <div class="item"></div> </div> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.