问题
I'm creating a online shop. I need to have 3 items per row with some space left over. So my idea was a column of 9 with 3 child columns of. Then I have 3 columns left over from the 9 for whaterever else I choose.
My issue is in a few categories I have 4/5 items. So they all appear on 1 line. How can I solved this.
<div class="container">
<div class="row">
<div class="col-md-9">
<div class="row">
@foreach ($items as $item)
<div class="col-md-3">
<img class="list-image" src="{{$item->image}}">
</div>
@endforeach
</div>
</div>
</div>
</div>
回答1:
Every row in bootstrap is 12 cols. It does not matter if you take you top row only 9 cols. Inside the 9 cols row you will have 12 cols again. Best thing in your case to do is calculate floor 12/<#items>. Then user the value to determine your col size.
回答2:
You don't have to use all 12 columns. 12 columns is just the maximum that's available. There is a number of ways to achieve the desired spacing between columns when you don't utilize all 12 of the available columns like it is in your case.
Two of the possible options would be to use the justify-content-around class or the justify-content-between class on the row like so (click "run code snippet" below and expand to full page):
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<div class="container bg-light my-3">
<h3 class="text-center pt-2">row justify-content-around</h3>
<div class="row justify-content-around">
<div class="col-md-3 bg-warning">Column 1</div>
<div class="col-md-3 bg-primary">Column 2</div>
<div class="col-md-3 bg-secondary">Column 3</div>
</div>
<h3 class="text-center pt-4">row justify-content-between</h3>
<div class="row justify-content-between">
<div class="col-md-3 bg-warning">Column 1</div>
<div class="col-md-3 bg-primary">Column 2</div>
<div class="col-md-3 bg-secondary">Column 3</div>
</div>
</div>
As you can see, no unnecessary nesting is needed there.
That's because those classes take advantage of the flexbox properties.
回答3:
You can use the auto-layout columns which are not restricted to 12.
Use .col-auto for columns that size to their content..
<div class="row">
<div class="col-auto">
<img class="list-image">
</div>
<div class="col-auto">
<img class="list-image">
</div>
<div class="col-auto">
<img class="list-image">
</div>
<div class="col-auto">
... to n
</div>
</div>
or, use .col for columns that evenly fill across the row..
<div class="row">
<div class="col">
<img class="list-image">
</div>
<div class="col">
<img class="list-image">
</div>
<div class="col">
... to n
</div>
</div>
Demo: https://www.codeply.com/go/wqoiLlSUc5
来源:https://stackoverflow.com/questions/49414441/n-number-of-columns-in-bootstrap-4