Html <ul> 包含浮动 <li> 时的高度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6751296/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 09:38:21  来源:igfitidea点击:

<ul> height when containing floating <li>

htmlcsshtml-listscss-float

提问by tsusanka

I have a list:

我有一个清单:

<ul>
 <li>Number 1</li>
 <li>Number 2</li>
 <li>Number 3</li>
 ...
</ul>

All the <li>are floating. I need the height of the <ul>box. If I remember correctly this is not valid:

所有的<li>浮动。我需要<ul>盒子的高度。如果我没记错的话,这是无效的:

<ul>
 <li>Number 1</li>
 <li>Number 2</li>
 <li>Number 3</li>
 ...
 <hr class="clear" />
</ul>

.clear {
   clear: both;
}

How can I do this? The number of items in the list can be different so I can't use fixed height.

我怎样才能做到这一点?列表中的项目数量可能不同,所以我不能使用固定高度。

回答by thirtydot

Good options to contain the floats:

包含浮动的好选择:

回答by Trevor

This isn't a direct answer to your question, but as an alternative could you consider using display:inline-block? These days I just use that instead of floatwhere possible, as essentially most of the time it can achieve the same sort of objective without the total hassle of making containers properly contain inner floating elements and having to clearthem all the time.

这不是您问题的直接答案,但作为替代方案,您可以考虑使用display:inline-block? 这些天我只是使用它而不是float在可能的情况下使用它,因为基本上大多数时候它可以实现相同的目标,而无需让容器正确包含内部浮动元素并一直使用clear它们。

回答by ali youhannaei

test it:

测试一下:

ul { overflow: hidden; }
li { float:right; display:block; }

add class to your elements, don't do this for all elements.

为您的元素添加类,不要对所有元素都这样做。

回答by Husen

Here, i am presenting, one of the easiest way to handle this kind of situations.

在这里,我将介绍处理这种情况的最简单方法之一。

Float left always have some reaction and not good to use if we have some alternative of it.

Float left 总是有一些反应,如果我们有其他选择,就不好用了。

The Alternative is :

替代方案是:

li { display:inline-block; }

No need to add extra code like float:left and overflow:hidden :)

无需添加额外的代码,如 float:left 和 overflow:hidden :)