Reputation: 165
I have fetched some list of destinations cities from database and want to show it in view.
here is my normal approach
<?php
$this->db->select('*');
$citydata = $this->db->get('cities')->result_array();
foreach ($citydata as $citydatas){?>
<div class="col-lg-4">
<img src="<?=$citydatas['banner];?>" />
</div>
<? } ?>
Above code will display 3 columns in each row,
But What i want is different approach, I need to show 2 columns in first row, then 3 column in second row.
and
Another Approach would be - three column in first row but first column will take half screen and other two will take another half and in second row first two will take half and then third will take rest half screen using col-6
here is the first grid style what i am looking for
here is the second grid style
My Approach for first style, is below approach good to use?
<?php
$this->db->select('*');
$citydata = $this->db->get('cities')->result_array();
$i = 1;
foreach ($citydata as $citydatas){?>
<div class="<?php if($i++ == 1 || $i++ == 2){ echo "col-lg-6";}else{echo"col-lg-4";}?>">
<img src="<?=$citydatas['banner];?>" />
</div>
<? } ?>
Upvotes: 1
Views: 1340
Reputation: 29281
You can use nth-child
selector along with CSS grid to get the desired result.
First Grid Style
.grid-container {
display: grid;
grid-template-columns: repeat(4, 1fr);
grid-gap: 10px;
grid-auto-rows: 200px;
}
img:nth-child(6n + 1),
img:nth-child(6n + 2){
grid-column: span 2;
}
img {
width: 100%;
height: 100%;
}
<div class="grid-container">
<img src="https://picsum.photos/id/10/400" />
<img src="https://picsum.photos/id/20/400" />
<img src="https://picsum.photos/id/30/400" />
<img src="https://picsum.photos/id/40/400" />
<img src="https://picsum.photos/id/50/400" />
<img src="https://picsum.photos/id/60/400" />
</div>
Second Grid Style
For second grid style, you just need to change the nth-child
selector, rest of the code will be same.
img:nth-child(6n),
img:nth-child(6n + 1) {
grid-column: span 2;
}
.grid-container {
display: grid;
grid-template-columns: repeat(4, 1fr);
grid-gap: 10px;
grid-auto-rows: 200px;
}
img:nth-child(6n),
img:nth-child(6n + 1) {
grid-column: span 2;
}
img {
width: 100%;
height: 100%;
}
<div class="grid-container">
<img src="https://picsum.photos/id/10/400" />
<img src="https://picsum.photos/id/20/400" />
<img src="https://picsum.photos/id/30/400" />
<img src="https://picsum.photos/id/40/400" />
<img src="https://picsum.photos/id/50/400" />
<img src="https://picsum.photos/id/60/400" />
</div>
PHP Code
Use following code to render this layout using PHP
<div class="grid-container">
<?php foreach($citydata as $citydatas): ?>
<img src="<?=$citydatas['banner]?>"/>
<?php endforeach; ?>
</div>
Upvotes: 1