Html 如何强制 div 元素将其内容保留在容器内

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11219931/
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 01:17:40  来源:igfitidea点击:

How to force div element to keep its contents inside container

htmlcss

提问by Om3ga

I am making a css menu. For this I am using a ul. When I make lifloat left then all li's gets outside of the ul. I mean the height of ulbecome zero. How can I make lidisplay inside ulafter giving float left.

我正在制作一个 css 菜单。为此,我正在使用ul. 当我li向左浮动时,所有li的都超出了 ul。我的意思是高度ul为零。向左浮动后如何li在内部显示ul

One way to do is to make a divtag with some common class and add clear: both to it in css but I do not want this.

一种方法是div使用一些公共类创建一个标签并添加 clear: 两者都在 css 中,但我不想要这个。

How can I solve this?

我该如何解决这个问题?

回答by Nathanael

Just add overflow: auto;to the <ul>. That will make it so that the text doesn't leak outside of the UL.

只需添加overflow: auto;<ul>. 这将使文本不会泄漏到 UL 之外。

See: http://jsfiddle.net/6cKAG/

见:http: //jsfiddle.net/6cKAG/



However, depending on what you're doing, it might be easier to just make the <li>display: inline;. It totally depends on what you're doing!

但是,根据您的操作,将<li>display: inline;. 这完全取决于你在做什么!

See: http://jsfiddle.net/k7Wqx/

见:http: //jsfiddle.net/k7Wqx/

回答by sandeep

If you define floatto your child then you have to clear your parent. Write overflow:hiddento your UL.

如果您定义float给您的孩子,那么您必须清除您的父母。写信overflow:hidden给您的 UL。

ul{
 overflow:hidden;
}

ORYou can also use clearfixmethod for this:

或者您也可以clearfix为此使用方法:

ul:after{
 content:'';
 clear:both;
 display:block;
}

Read this http://css-tricks.com/snippets/css/clear-fix/

阅读这个http://css-tricks.com/snippets/css/clear-fix/

回答by Rahi.Shah

If you want the overflowing text in the div to automatically newline instead of being hidden or making a scrollbar, use the

如果您希望 div 中的溢出文本自动换行而不是被隐藏或制作滚动条,请使用

word-wrap: break-word

property.

财产。

回答by o.v.

This happens when floated elements (menu items) are positioned inside a non-floating container (ul).

当浮动元素(菜单项)位于非浮动容器 ( ul)内时,就会发生这种情况。

This could either be fixed by floating the container as well (rarely acceptable), or applying a clearfixwhich addresses exactly this issue.

这可以通过浮动容器来解决(很少接受),或者应用一个明确解决这个问题的 clearfix