问题描述
我不想用块内容自动填充空间.我希望等宽块之间的间距相等,这也很灵活.
I don't want to auto fill space with blocks content. I want equal spacing between fixed-width blocks, that would also be flexible.
我可以通过添加padding-right: whatever;
然后在.last
块中添加另一个padding-right: 0;
来做到这一点,但这是非常原始的,并且不是移动友好的.
I can do that by adding padding-right: whatever;
and then adding another padding-right: 0;
to .last
block, but that's very primitive and not mobile friendly.
我的代码: 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>
推荐答案
您可以使用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解决方案.我为每个block
元素计算了margin-left
,以在元素之间创建相等的间距.另外,必须删除HTML中的空白.
Here is js solution for older browsers that don't support Flexbox
. I calculated margin-left
for each block
element to create equal spacing between elements. Also white space from HTML must be removed.
$(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>
这篇关于如何在嵌入式块元素之间添加相等的空间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!