问题
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;
}
回答1:
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/
回答2:
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;
}
回答3:
or otherwise you could just use table with a single row, tr → td So it won't let the elements inside it wrap
来源:https://stackoverflow.com/questions/15567395/force-elements-to-be-horizontally-aligned