Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grid columns using flexbox with fixed size margin gutters

Is it possible to apply a fixed margin (e.g. 5px) to a cell in a flexbox layout, where the row space is evenly distributed among its columns?

Want I want to achieve:

this is the desired layout

My current CSS will only align 3 columns in one row:

JSFiddle

.row {
    display: flex;
    flex-flow: row wrap;
	box-shadow: 0 0 0 1px green;
}

.col {
    flex: 0 0 25%;
    text-align: center;
	box-shadow: 0 0 0 1px blue;
    background-color: steelblue;
	
	margin: 5px;
}
<div class="row">
    <div class="col">
		<div class="panel">1</div>
	</div>
    <div class="col">
		<div class="panel">2</div>
	</div>
    <div class="col">
		<div class="panel">3</div>
	</div>
    <div class="col">
		<div class="panel">4</div>
	</div>
	<div class="col"><div class="panel">5</div></div>
</div>
like image 236
Imperative Avatar asked Feb 09 '23 03:02

Imperative


1 Answers

You could use calc() for flex-basis length (in your case — it's in shorthand property flex), 10px because margin-left: 5px and margin-right: 5px:

JSFiddle

.row {
    display: flex;
    flex-flow: row wrap;
    box-shadow: 0 0 0 1px green;
}

.col {
    flex: 0 0 calc(25% - 10px);
    text-align: center;
    box-shadow: 0 0 0 1px blue;
    background-color: steelblue;
    margin: 5px;
}
<div class="row">
    <div class="col">
        <div class="panel">1</div>
    </div>
    <div class="col">
        <div class="panel">2</div>
    </div>
    <div class="col">
        <div class="panel">3</div>
    </div>
    <div class="col">
        <div class="panel">4</div>
    </div>
    <div class="col">
        <div class="panel">5</div>
    </div>
</div>
like image 121
sergdenisov Avatar answered Feb 11 '23 03:02

sergdenisov