8

Let's say I have random children in my div, which has fixed height and width set to 100% to breathe with the layout.

Which CSS must I use to force child elements to align horizontally and when the div's width is smaller then the content, display a scrollbar and not overlap one another?

Fiddle:http://jsfiddle.net/GRBc6/1/

simple css:

.parent{
    width:500px;
    height: 50px;
    background-color: red;
}
.kid{
    width: 150px;
    height: 20px;
     background-color: green;
    float:left;
    margin-left:4px; 
}
Jacob
  • 3,580
  • 22
  • 82
  • 146

3 Answers3

16

if you make the kid an inline-block element and take off the float:left, you can make the parent have white-space:nowrap and it will achieve what you want:

.parent{
    width:300px;
    height: 50px;
    background-color: red;
    white-space:nowrap;
    overflow-x:scroll;
}
.kid{
    width: 150px;
    height: 20px;
    background-color: green;
    display:inline-block;
    margin-left:4px;

}

http://jsfiddle.net/GRBc6/6/

Pete
  • 57,112
  • 28
  • 117
  • 166
0

You need to add 2 properties to .parent: overflow-x:scroll and white-space:nowrap, and change the float property of kids to display: inline-block. Here's working code:

.parent{
    width:500px;
    height: 50px;
    background-color: red; 
    overflow-x: scroll;
    white-space: nowrap;
}
.kid{
    width: 150px;
    height: 20px;
    background-color: green;
    margin-left:4px; 
    display: inline-block;
}
Pasha
  • 6,298
  • 2
  • 22
  • 34
-1

or otherwise you could just use table with a single row, trtd So it won't let the elements inside it wrap

user26981
  • 9
  • 1
  • Tables are for tabular data – Pete Mar 22 '13 at 10:35
  • it is ok to use this way if the container div isn't fixed – user26981 Mar 22 '13 at 10:54
  • I guess you're not bothered about coding standards then http://www.w3.org/WAI/wcag-curric/sam48-0.htm – Pete Mar 22 '13 at 10:56
  • I was worried more about how to make horizontal gallery with non-fixed width via css, but couldn't figure it out. can you propose any solution for that? – user26981 Mar 22 '13 at 11:03
  • Because if you won't make the container element fixed width, all those whitespace and inline-block elements won't work, so the contents will wrap as well. And if I don't know actual width of the gallery (which I can't know, as far as content is added dynamically), you cannot specify it's width like that. – user26981 Mar 22 '13 at 11:13
  • you can just set the width of the parent container as 100% and use the above styles to make the content have a horizontal scroller if the number of boxes is greater than 100% width – Pete Mar 22 '13 at 11:16
  • but won't it look like an iframe, adding extra scroll. The point was to make the whole page horizontal, no matter what width it will have – user26981 Mar 22 '13 at 11:25