Organizing Pictures in a Gridded Design

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.

Answer №1

My suggestion would be to utilize $("#outer").innerWidth() when determining the value of maxCount. This approach takes into account any padding within the container and focuses on the inner portion of the element.

To resolve the issue, you can add the following code:

box-sizing: border-box;
-moz-box-sizing: border-box;

to the #outer div in order to preserve its width. However, I've noticed a discrepancy where there is slightly more space on the right side compared to the left. Additionally, there are mysterious white spaces between the divs (as shown in the screenshot) that seem to be unaffected by any CSS styles. These spaces may be impacting the calculation, resulting in slightly excessive left-padding.

You can view the example on jsFiddle here.

Answer №2

Here is the solution: http://jsfiddle.net/dan_barzilay/fy494/

To center the images, instead of adjusting the left padding of #outer by freeSpace / 2, I changed both the padding-right and padding-left using freeSpace / 4. This kept the images centered properly.

$("#outer").css({"padding-left": freeSpace / 4, "padding-right": freeSpace / 4});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Aligning the column to the right to ensure the text is centered horizontally on the screen

<div className={css.title} > <div className={css.row}> <div className={css.columnLeft}> <div className={css.header}>Images</div> </div> <div className={css.col ...

Applying CSS styling to PHP documents

I am a beginner, so please go easy on me. I am looking to style variables like $product_name, $author, and $details. I was thinking of styling the echos, but in this scenario, the only echo is: <?php // Establish connection with the MySQL database ...

Ways to forward from an ajax-triggered action

I am looking to immediately redirect from the "Login" action to the "Home" action without going through the ajax success callback. Currently, when the "Login" action is triggered via ajax, it redirects to the "Home" action, but the ajax success callback st ...

PHP Database Query Automation

Looking to continuously query a database every .5 seconds in PHP to check for a specific field's status. Although I have achieved this functionality in Java, I am uncertain how to implement it in PHP due to the lack of threading support. While researc ...

When a user clicks anywhere on the website, the active and focused class will be automatically removed

I'm currently working with Bootstrap tabs on my website. I have three tabs, and when a user clicks on one, the active and focus classes are added to indicate which tab is selected. However, I've encountered an issue where clicking anywhere else ...

Show the content of a div inside a tooltip message box in an MVC application

I have a MVC application where I need to show tooltip messages when hovering over my HTML div. HTML: <li class="Limenu" data-placement="right"> <span class="LessMenuspan btn-primary" pid="@i.ConsumerNo_" onmouseover="FacebookprofileTip(1, 0,thi ...

Unusual behavior observed in Angular 2 when handling button click events

In my .ts file, there are two straightforward methods: editLocation(index) {} deleteLocation(index) { this.locations.splice(index, 1); } The corresponding HTML triggers these methods when buttons are clicked: <button (click)="editLocation(i)" ...

The dropdown menu fails to update in Internet Explorer

Here is the URL for my website: . On this page, there are two fields - category and subcategory. When a category is selected, the corresponding subcategory should change accordingly. This functionality works smoothly in Google Chrome, however it encounte ...

What are the steps to customize the format of Vue3 Datepicker extensions?

Is there anyone who can lend a hand? I am currently using the Vue3 Datepicker and I have received a value that looks like this Thu Jun 23 2022 17:14:00 GMT+0700 (Western Indonesia Time) Does anyone know how to transform it into the following format? Thu, ...

What is the best way to transform URL images on a webpage into media library images in WordPress?

Having trouble converting HTML Static Sites to WordPress because images are hosted through HTML SRC Code. After conversion, no one can see the images in visual format on pages during editing. Is there a way to convert all image links inside pages to media ...

What is the method for converting a string into HTML formatting?

I am working on a Django project. My goal is to display an output string on an HTML page. Here is my view: def strategy_run(request): output = "hello world!\nstring test" return render_to_response('strategy_run.html', locals()) T ...

How can a div tag and its class be nested using CSS in Angular?

Can someone help me with nesting a div tag with the "error" class in CSS? <div [class]="{error: condition}">{{ message }}</div> I want to know how to have the .error selector inside the div selector in the CSS file. Note: The error ...

What is the best way to ensure a consistent spacing between two flex items?

I am working on a project to enhance my knowledge by rebuilding Facebook. One of the new concepts I am learning is Flexbox. When you resize the login page of Facebook, you'll notice that the Navigation shrinks but the logo and login inputs remain sta ...

Using jQuery with multiple selectors can become tricky when dealing with elements that may or may not be present

I decided to be more efficient by using multiple selectors instead of rewriting the same code repeatedly. Typically, if one element exists then the others do not. $('form#post, form#edit, form#quickpostform').submit( function() { ...

Attempting to remove the initially added div by utilizing a button results in the deletion of the subsequent appended div in jQuery

Suppose there are 2 appended divs inside a main div. When attempting to remove the first appended div using the revoke button, it initially removes the second appended div. However, if the revoke button is clicked again on the first div, it then removes th ...

Dynamically change the fill color of an SVG using styled-components

I've been attempting to target the fill property of my SVG using CSS in styled-components without any luck. Here is my SVG: <svg width="65" height="19" viewBox="0 0 65 19" fill="none" xmlns="http://www. ...

Attempting to utilize Bootstrap for containing text inside of a background

<div class="container"> <div class="row"> <div class="col-lg-9"> <h2 style="font-family:times-new-roman">BIOGRAPHY</h2> <div id="demo" class="collapse"> <p> Isaac Newton (4 January 1643 – 31 March 1727) w ...

jQuery unable to access data from cross-origin JSON service URL

Similar Question: Issues with JQuery not receiving JSON data? <script type="text/javascript> var url = "http://local.yahooapis.com/LocalSearchService/V3/localSearch?appid=YahooDemo&query=pizza&zip=10504&results=2&output=j ...

Struggles with ajax and JavaScript arise when attempting to tally up grades

Currently, I am facing an issue with my JavaScript. The problem arises when trying to calculate marks for each correctly chosen answer based on information from the database. If an incorrect answer is selected, the marks are set to '0', otherwise ...

What is the best way to adjust the content of a Bootstrap Column to be at the bottom of the column

Currently diving into the world of Bootstrap for my personal website, I'm encountering a challenge in aligning the content of my sidebar to the bottom. My quest for a solution led me through numerous threads without success. <!-- wordsmith: < ...