简体   繁体   中英

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.

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

#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. For this issue, browser compatibility is a non-issue.

我有的

What I have

我想要的是

What I want

jsfiddle

Use white-space: nowrap; on #inner

Fiddle

White space property

i dont't know if i get your question right, but have you tried it with

overflow-x: scroll;
overflow-y: hidden;

UPDATED FIDDLE

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 .

In fact, I'm not sure you need the ul at all as you can achieve what you are after without it.

I have widened the outer div in the Fiddle so you can see what is going on

JSfiddle Demo

 #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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM