CSS-让 div 水平对齐

我有一个带有固定 widthheight的容器 div,带有 overflow: hidden

我想要一个浮动的水平行: 容器内的左 div。浮动在左边的 Div 在读取其父级的右边界后,自然会推到下面的“行”上。即使父代的 height不允许这样做,也会发生这种情况。看起来是这样的:

Wrong

我希望它看起来怎么样:

! [右][2]-已经被广告取代的图像棚屋图像

注意: 我想要的效果可以通过使用内联元素和 white-space: no-wrap来实现(这就是我在图中所做的)。但是,这对我没有好处(原因太长,无法在这里解释) ,因为子 div 需要浮动块级别的元素。

236900 次浏览

This seems close to what you want:

#foo {
background: red;
max-height: 100px;
overflow-y: hidden;
}


.bar {
background: blue;
width: 100px;
height: 100px;
float: left;
margin: 1em;
}
<div id="foo">
<div class="bar"></div>
<div class="bar"></div>
<div class="bar"></div>
<div class="bar"></div>
<div class="bar"></div>
<div class="bar"></div>
</div>

you can use the clip property:

#container {
position: absolute;
clip: rect(0px,200px,100px,0px);
overflow: hidden;
background: red;
}

note the position: absolute and overflow: hidden needed in order to get clip to work.

You may put an inner div in the container that is enough wide to hold all the floated divs.

#container {
background-color: red;
overflow: hidden;
width: 200px;
}


#inner {
overflow: hidden;
width: 2000px;
}


.child {
float: left;
background-color: blue;
width: 50px;
height: 50px;
}
<div id="container">
<div id="inner">
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
</div>
</div>

style="overflow:hidden" for parent div and style="float: left" for all the child divs are important to make the divs align horizontally for old browsers like IE7 and below.

For modern browsers, you can use style="display: table-cell" for all the child divs and it would render horizontally properly.

Float them left. In Chrome, at least, you don't need to have a wrapper, id="container", in LucaM's example.

Float: left, display: inline-block will both fail to align the elements horizontally if they exceed the width of the container.

It's important to note that the container should not wrap if the elements MUST display horizontally: white-space: nowrap

You can now use css flexbox to align divs horizontally and vertically if you need to. general formula goes like this

parent-div {
display: flex;
flex-wrap: wrap;
/* for horizontal aligning of child divs */
justify-content: center;
/* for vertical aligning */
align-items: center;
}


child-div {
width: /* yoursize for each div */
;
}