I don't want to auto fill space with blocks content. I want equal spacing between fixed-width blocks, that would also be flexible.
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.
My code: 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>
You could use Flexbox
and 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>
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With