我不想用块内容自动填充空间。我希望固定宽度的块之间的间距相等,这也是灵活的。
我可以通过添加padding-right: whatever;
,然后将另一个padding-right: 0;
添加到.last
块来实现这一点,但这非常原始且不适合移动设备。
我的代码:https://jsfiddle.net/9twy5drd/1/
.container {
width: 100%;
border: 1px solid red;
text-align: center;
padding: 5px 0;
}
.container .block {
display: inline-block;
border: 1px solid green;
padding: 10px;
}
.container2 {
width: auto;
border: 1px solid red;
padding: 5px;
}
.container2 .block {
display: inline-block;
border: 1px solid green;
padding: 10px;
margin: 0 47px 0 0;
}
.container2 .block.last {
margin: 0;
}
<div class="container">
<div class="block">Some block</div>
<div class="block">Some block</div>
<div class="block">Some block</div>
<div class="block">Some block</div>
</div>
<p>What we want, but not with fixed method:</p>
<div class="container2">
<div class="block">Some block</div>
<div class="block">Some block</div>
<div class="block">Some block</div>
<div class="block last">Some block</div>
</div>
答案 0 :(得分:3)
您可以使用Flexbox
和justify-content: space-between;
.container {
width: 100%;
border: 1px solid red;
text-align: center;
display: flex;
flex-wrap: wrap;
justify-content: space-between;
padding: 5px 0;
}
.container .block {
border: 1px solid green;
padding: 10px;
}
<div class="container">
<div class="block">Some block</div>
<div class="block">Some block</div>
<div class="block">Some block</div>
<div class="block">Some block</div>
</div>
以下是不支持Flexbox
的旧浏览器的js解决方案。我为每个margin-left
元素计算了block
,以便在元素之间创建相等的间距。还必须删除HTML中的空格。
$(window).on("resize", function() {
var block = $('.container > .block');
var count = block.length;
var bWidth = block.outerWidth();
var pWidth = $('.container').innerWidth();
var margin = (pWidth - (bWidth * count)) / (count - 1);
if (margin > 0) block.not(':last').css('margin-right', margin);
}).resize();
.container {
width: 100%;
border: 1px solid red;
text-align: center;
padding: 5px 0;
}
.container .block {
border: 1px solid green;
display: inline-block;
padding: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="block">Some block</div><div class="block">Some block</div><div class="block">Some block</div><div class="block">Some block</div>
</div>
答案 1 :(得分:0)
只需justify
您的容器,不要忘记使用text-align-last
(Firefox 49及更新版本不需要前缀)
.container {
width: 100%;
border: 1px solid red;
text-align: justify;
-moz-text-align-last: justify;
text-align-last: justify;
padding: 5px;
}
.container .block {
display: inline-block;
border: 1px solid green;
padding: 10px;
}
&#13;
<div class="container">
<div class="block">Some block</div>
<div class="block">Some block</div>
<div class="block">Some block</div>
<div class="block">Some block</div>
</div>
&#13;