My dilemma lies in displaying a set of thumbnail images within a div
. The width of the div can vary depending on the screen size. Each image is fixed at 150px * 150px
with a padding of 5px
. I aim to arrange these thumbnails in a grid layout while ensuring they are centered within the outer div. Initially, I tried using text-align: center
on the outer div.
However, this resulted in the images on the last row being centered when what I really wanted was for them to align from the left. So, I devised a plan to calculate the free space available after placing the images and apply a padding-left (=freespace/2)
to the outer div to achieve a center-aligned appearance.
This is the code snippet I currently have:
CSS
#outer {
border: 1px solid;
resize: horizontal;
overflow: auto;
width: 700px;
padding: 0;
}
.inner {
width: 150px;
height: 150px;
background: #ccc;
padding: 5px;
display: inline-block;
}
jQuery
$(document).ready(function() {
$("#position").click(function() {
var maxCount = Math.floor($("#outer").outerWidth() / $(".inner").outerWidth());
console.log("maxcount::" + maxCount);
var freeSpace = $("#outer").outerWidth() - ($(".inner").outerWidth() * maxCount);
console.log("freeSpace::" + freeSpace);
$("#outer").css("padding-left", freeSpace / 2);
});
$("#text").toggle(function() {
$("#outer").css("text-align","center");
},function(){
$("#outer").css("text-align","left");
});
});
HTML
<button id="position">
Adjust position
</button>
<button id="text">
Toggle text align
</button>
<div id="outer">
<div class="inner"></div>
<div class="inner"></div>
<div class="inner"></div>
<div class="inner"></div>
<div class="inner"></div>
<div class="inner"></div>
<div class="inner"></div>
</div>
You can view a demo here - http://jsfiddle.net/userdude/fzjrm/1/
Despite my efforts, the content does not appear perfectly center aligned. It seems like the logic behind it may need some tweaking, but I'm currently unable to pin down the issue.