Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Horizontal scrolling with overflow-x

I was wondering if there still isn't a good way to get a div to stretch and scroll horizontally, according to the images inside. After all, it is 2011 now!

The mega-width does the trick, but leaves an empty mega-space if not filled with images.
If filled too much, images don't display. Same for the jQuery. The situation below is the best I can do after hours of Googling, but it isn't reliable enough.

Thanks for your time.


* {
  margin:0;
  padding:0;
}

#one {
  width: 200px;    
  height: 250px;
  overflow-x: auto;
  overflow-y: hidden;
}

#two {
  width: 10000em;
}

#two img {
  float: left;
}

$(document).ready(function() {
  var total = 0;
  $(".calc").each(function() {
    total += $(this).outerWidth(true);
  });
  $("#two").css('width', total);
  alert(total);
});
<div id="one">
  <div id="two">
    <img src="images/testimage3.jpg" width="480" height="192" class="calc">
    <img src="images/testimage3.jpg" width="480" height="192" class="calc">
    <img src="images/testimage3.jpg" width="480" height="192" class="calc">
    <img src="images/testimage3.jpg" width="480" height="192" class="calc">
  </div>
</div>
like image 697
ams Avatar asked Jan 04 '11 04:01

ams


1 Answers

It's easy. display:inline-block on the images and white-space:nowrap on the parent.

Edit: I forgot that images are by default inline, anyway :) That means that white-space:nowrap is all you need.

div { 
    overflow-x:scroll;
    overflow-y:hidden;
    white-space:nowrap;
}

Live demo: http://jsfiddle.net/U4RsQ/2/

like image 180
Šime Vidas Avatar answered Oct 24 '22 18:10

Šime Vidas