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
How to force div element to keep its contents inside container
提问by Om3ga
I am making a css menu. For this I am using a ul
. When I make li
float left then all li
's gets outside of the ul. I mean the height of ul
become zero. How can I make li
display inside ul
after giving float left.
我正在制作一个 css 菜单。为此,我正在使用ul
. 当我li
向左浮动时,所有li
的都超出了 ul。我的意思是高度ul
为零。向左浮动后如何li
在内部显示ul
。
One way to do is to make a div
tag 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/
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;
. 这完全取决于你在做什么!
回答by sandeep
If you define float
to your child then you have to clear your parent. Write overflow:hidden
to your UL.
如果您定义float
给您的孩子,那么您必须清除您的父母。写信overflow:hidden
给您的 UL。
ul{
overflow:hidden;
}
ORYou can also use clearfix
method for this:
或者您也可以clearfix
为此使用方法:
ul:after{
content:'';
clear:both;
display:block;
}
回答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。