Hüseyin Dursun
Hüseyin Dursun

Reputation: 600

How to set width of a div to fit the contents?

I have serached all day and I couldn't find a solution to what I want to do. I know there are so many questions with this title, but none of them has worked for me.

What I am trying to do is a touch scrolling for mobile.

Here is my html:

    <body>
    <div id="slider_container"> 
         <div class="wrapper">
             <span>Image</span>
         </div>
    </div>
    </body>

There will be minimum 2 spans containing image and maximum 10 span containing images. There will some php codes and span number will change according to the uploaded photos by the user.

Here is my css code:

body
{
      width:100%;
      overflow-x:hidden;
}

#slider_container
{
width:100%;
height:320px;
overflow: scroll;
overflow-y: hidden;
-webkit-overflow-scrolling: touch;
}

.wrapper
{
position:absolute;
height:320px;
}

.wrapper img
{
max-width:310px;
max-height:310px;
margin-right:5px;
float:left;
}

What I want is to give .wrapper automatic width and overflowing outside of #slider_container and body.

I hope I could tell clearly.

Thanks for all answers...

Upvotes: 6

Views: 9465

Answers (1)

bfavaretto
bfavaretto

Reputation: 71939

You'll have to use JavaScript to measure the contents, then set the wrapper's width accordingly. Something like this:

var spans = document.querySelectorAll('.wrapper span');
var width = 0;
for(var i=0; i<spans.length; i++) {
    width += spans[i].offsetWidth + 5; // + 5 for the margins
}
document.querySelector('.wrapper').style.width = width + 'px';

Alternate code for multiple sliders:

var wrappers = document.querySelectorAll('.wrapper');
var width;
for(var i=0; i<wrappers.length; i++) {
    var spans = wrappers[i].querySelectorAll('span');
    width = 0;
    for(var j=0; j<spans.length; j++) {
        width += spans[j].offsetWidth + 5; // + 5 for the margins
    }
    wrappers[i].style.width = width + 'px';
}

http://jsfiddle.net/s4RxE/1

Upvotes: 2

Related Questions