我试图让多个div占用父div的整个宽度。为了做到这一点,我使用了display:table
和display:table-cell
。这种方法的问题是我不能为子div添加边距以便在它们之间留出一些空间。现在他们都堆叠在一起,看起来不太好。
有什么建议?
这是代码:
.parent {
text-align:center;
margin:0px;
width:500px;
padding:0px;
background:blue;
display:table;
box-sizing:border-box;
-moz-box-sizing:border-box;
-webkit-box-sizing:border-box;
list-style-type:none;
}
.child{
padding:15px;
background:#f00;
display:table-cell;
list-style-type:none;
}
.child:nth-child(2n) {background:green;}
<div class="parent">
<div class="child">sometext</div>
<div class="child">somemoretext</div>
<div class="child">sometext</div>
<div class="child">sometext</div>
</div>
Flexbox让你:):
Body {background:cyan;}
.parent {
text-align:center;
margin:0px;
width:100%;
padding:0px;
background:blue;
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
-webkit-box-pack: justify;
-webkit-justify-content: space-between;
-ms-flex-pack: justify;
}
.child{
padding:15px 25px;
background:#f00;
list-style-type:none;
width:inherit;
margin:5px;
}
.child:nth-child(2n) {background:green;}
<div class="parent">
<div class="child">sometext</div>
<div class="child">somemoretext</div>
<div class="child">sometext</div>
<div class="child">sometext</div>
</div>
<div class="parent">
<div class="child">somemoretext</div>
<div class="child">sometext</div>
</div>
<div class="parent">
<div class="child">somemoretext</div>
<div class="child">somemoretext</div>
<div class="child">sometext</div>
</div
>
您可以通过添加border
来添加空间:
.parent {
text-align:center;
margin:0px;
width:500px;
padding:0px;
background:blue;
display:table;
box-sizing:border-box;
-moz-box-sizing:border-box;
-webkit-box-sizing:border-box;
list-style-type:none;
}
.child{
padding:15px;
background:#f00;
display:table-cell;
list-style-type:none;
border-left:10px solid #fff;
border-right:10px solid #fff;
}
.child:nth-child(2n) {background:green;}
<div class="parent">
<div class="child">sometext</div>
<div class="child">somemoretext</div>
<div class="child">sometext</div>
<div class="child">sometext</div>
</div>
而不是使用display:table和table-cell,使用display:inline-block;。然后给出你想要的边距。
.parent {
text-align:center;
margin:0px;
width:500px;
padding:0px;
background:blue;
display:inline-block;
box-sizing:border-box;
-moz-box-sizing:border-box;
-webkit-box-sizing:border-box;
list-style-type:none;
}
。儿童{
margin:5px;
background:#f00;
display:inline-block;
list-style-type:none;
}
.child:nth-child(2n){
background:green;
}