I am currently working on setting up a responsive grid within my HTML code. The content is contained within a bootstrap .container
and consists of multiple div elements. The number of these divs can vary based on external factors, and I need the layout to adapt accordingly. If there are an even number of divs, I want them to be arranged in a 2xn grid format. However, if there's an odd number of divs, I still want a grid layout but with the last div centered in its own block.
HTML
<div class="container">
<div class="targetcontainer">
<div class="target">
<p>content goes here man</p>
</div>
<div class="target">
<p>content goes here man</p>
</div>
<div class="target">
<p>content goes here man</p>
</div>
<div class="target">
<p>content goes here man</p>
</div>
<div class="target">
<p>content goes here man</p>
</div>
</div>
</div>
CSS
.target {
display: inline-block;
width: 47%;
min-width: 400px;
height: 265px;
margin: 10px 10px;
padding: 2%;
vertical-align: top;
background: #fff;
border: 1px solid #ebebeb;
text-decoration: none;
-webkit-transition: all 0.2s;
-moz-transition: all 0.2s;
-o-transition: all 0.2s;
-ms-transition: all 0.2s;
transition: all 0.2s;
border-bottom: 3px solid transparent;
cursor: pointer;
}
JS
function addClassToLastElement() {
$('.target').each(function(index, element) {
if ($(this).is(":last-child") && index % 2 == 0) {
$(this).css('display', 'block')
$(this).css('margin', '0 auto')
}
})
}
addClassToLastElement()
In my jQuery script, I check for the presence of an odd number of elements and apply specific styling to center the last div accordingly. You can view this functionality here (ensure that the screen size is relatively large).
However, an issue arises when the screen is resized. As the divs stack on top of each other, they don't center consistently except for the last one. Ideally, all the divs should align in the middle of the screen as they stack vertically. Is there a way to achieve this without relying on Bootstrap or using jQuery's .resize()
function? My goal is to use only one Bootstrap element, specifically the .container
.