Force elements to be horizontally aligned

假装没事ソ 提交于 2019-12-30 09:29:12

问题


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, trtd So it won't let the elements inside it wrap



来源:https://stackoverflow.com/questions/15567395/force-elements-to-be-horizontally-aligned

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!