javascript 我怎样才能包装 div?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11517415/
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 can I wrap divs?
提问by wrongusername
Basically, I want the inner divs outside the outer div to wrap according to the width of the outer div, which in turn expands and contracts according to the width of the browser window, like so:
基本上,我希望外部 div 之外的内部 div 根据外部 div 的宽度进行包装,然后根据浏览器窗口的宽度进行扩展和收缩,如下所示:
.---------------------.
| | <-- Browser Window
| .-----------------. |
| | ,-, ,-, ,-, | |
| | |X| |X| |X| | |
| | `-` `-` `-` | |
| | | |
| | ,-, ,-, ,-, | |
| | |X| |X| |X| | |
| | `-` `-` `-` | |
| `-----------------` |
| |
`---------------------`
.-------------------------------.
| | <-- Browser Window enlarged
| .---------------------------. |
| | ,-, ,-, ,-, ,-, ,-, | |
| | |X| |X| |X| |X| |X| <----- Inner divs wrap around accordingly, as if
| | `-` `-` `-` `-` `-` | | they are text
| | | |
| | ,-, | |
| | |X| | |
| | `-` | |
| `---------------------------` |
| |
`-------------------------------`
What would be the best (as in simplest in terms of developer time) way to make this happen?
实现这一目标的最佳方法是什么(就开发人员时间而言最简单)?
回答by Lukas
Set for this blocks - display: inline-block
, and for main container some width...
为这个块设置 - display: inline-block
,并为主容器设置一些宽度...
.div {
display: inline-block;
}
回答by Jon Newmuis
You can just apply float: left
to each of the inner divs. See the following jsFiddle as an example (try resizing the result pane to see the behavior):
您可以只应用于float: left
每个内部 div。请参阅以下 jsFiddle 作为示例(尝试调整结果窗格的大小以查看行为):
jsFiddle (Live): http://jsfiddle.net/guh5Z/
jsFiddle(直播):http: //jsfiddle.net/guh5Z/
Source Code:
源代码:
<html>
<head>
<style type="text/css">
#outer {
width: 90%;
height: 90%;
margin: 5%;
overflow: auto;
background-color: red;
}
.inner {
float: left;
width: 150px;
height: 150px;
margin: 20px;
background-color: blue;
}
</style>
<body>
<div id="outer">
<div class="inner">X</div>
<div class="inner">X</div>
<div class="inner">X</div>
<div class="inner">X</div>
<div class="inner">X</div>
<div class="inner">X</div>
</div>
</body>
</html>
回答by Mohamed Turki
You could use <ul>
instead if you'll put text instead. Something like this :
你可以使用<ul>
,而不是如果你会把文字。像这样的事情:
CSS:
CSS:
ul {
margin: 0;
padding: 0;
list-style: none;
}
li {
width: 100px;
height: 120px;
border: 1px solid;
float: left;
margin: 5px;
}
HTML:
HTML:
<ul>
<li>Random text here</li>
<li>Random text here</li>
</ul>
I hope that helps
我希望有帮助