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

Creating a New Section in your HTML Table

Can a page break be implemented in an HTML table? I've attempted to add page breaks to the following HTML: <html> <title>testfile</title> <meta http-equiv="expires" content="0" /> <meta http-equiv="cache-contr ...

The background-size property in CSS does not seem to properly display on iPhones

Hello there! I'm facing an issue with my CSS code when it comes to displaying the image on Safari browser. It works perfectly fine on other browsers, but for some reason on Safari, the image doesn't show up correctly. I tried using a media query ...

Removing HTML tags and then reapplying HTML tags Part 1

Attempting to convert the following string: <p> string <b> bold <em>italic string</em> also(bold) </b> </p> to this modified string: <p> string </p> <!----------- ...

Embrace the words enveloped within large quotation marks

I am seeking a way to format paragraphs with large quotation marks surrounding them. I have attempted several methods, but my line-height seems to be affected, as shown in the following image: Can anyone suggest a proper method for achieving this? (Addit ...

How can I place my container above my header in the layout?

I'm facing difficulty positioning the container above my header. Here is an example of what I am aiming for: No matter what I attempt, strange occurrences like the NAV disappearing or divs overlapping keep happening. HTML: <!DOCTYPE html PUBLIC ...

Steps for removing jquery-1.7.min.js

My current project relies on jquery-1.7.min.js. I am looking to replace this code that uses jquery-1.7.min.js. For example, how can I modify the following code snippet? $(this._divArrContextMenuItem[i]).bind("mouseover", oContextMenuItem, ...

Expanding rows in Angular UI-Grid: Enhancing user experience with hover functionality

Struggling to add a hover effect to the rows in an Angular UI grid. The goal is for the entire row to change background color when hovered over, but with an expandable grid that includes a row header, applying CSS rules only affects either the row header o ...

Is it possible to retrieve the decimal value from the KendonumericTextbox?

Is there a way to retrieve the decimals and format properties value? var mileagerate = $("#mileagerate").kendoNumericTextBox({ decimals: 2, format: "c2", min: 0.00, step: 0.01 }).data("kendoNumericTextBox"); I'm looki ...

iOS devices will not scroll horizontally if there is a div that scrolls vertically within a div that scrolls horizontally

Picture a div that scrolls horizontally, housing two vertical-scrolling divs. You'll need to scroll left and right to navigate, then up and down inside the inner divs to read the content. /* RESET TO MINIMUM */ body, html { height: 100%; mar ...

"Error encountered: JSON trace not valid when making a jQuery AJAX request

$.ajax({ type: 'POST', headers: { "cache-control": "no-cache" }, url: '/Service.asmx/ProcessRequest', async: true, cache: false, data: 'controller=cart&add=1&ajax=true&qty ...

Adapting the position of a table row in AngularJS based on the

I need assistance with creating a dynamic table-row that moves to indicate the current time in a table filled with timestamps. <table> <tr ng-repeat="timestamp in timestampArray"> <td>{{timestamp}}</td> </tr> ...

Angular - send multiple HTTP requests for the length of an array and combine the responses into one array

Exploring angular for the first time and dabbling with the trello API. I have an array containing some list IDs that I need to make HTTP GET calls for, equal to the length of the array. For instance, if there are two IDs in the array, then the HTTP call sh ...

Version 1 of Vue.js is not compatible with Ajax-loaded HTML files

Currently, I am encountering a minor issue with loading content through ajax requests. I am in the process of developing a web application where everything is located on one page without any reloading. To achieve this, I have split the content into separa ...

Ensure that all items are centered while positioning one in the corner

Lately, I've been diving into the world of flexbox and trying out new things. However, there are still some concepts that elude me. My current project involves creating a straightforward layout with three flex items (children). The container is confi ...

Utilizing offsets/push in the correct manner

I have been developing a Bootstrap website and I wanted to get some feedback on my current code structure. The design is coming along nicely, but I am unsure if this aligns with best practices? <div class="container-fluid"> <div class="row"> ...

Is Jquery compatible with your Wordpress theme?

My current wordpress version is 3.4.1 and I want to include jQuery in my custom wordpress theme. Despite trying multiple solutions found online, I have been unsuccessful in implementing it convincingly. Can someone please provide a simple example to help ...

Enhanced auto-zoom feature with orientation change for iOS 7

My web page was functioning perfectly until the release of iOS 7 by Apple today, causing the layout to break when the screen orientation is changed. When focusing on a text area and rotating the screen to landscape view, the entire page zooms in. However, ...

What steps can I take to eliminate the initial delay when it is first invoked?

My function is being called every 10 minutes like this: var interval = self.setInterval(my_func, 600000); function my_func(){ $.ajax({ url: 'xxxxxxxx', success: function(response) { var data= JSON.parse(response); dis ...

Utilize the full width available to create a flexible div element without any fixed sizes

I have come across similar questions, but none of them quite addressed my specific situation. My dilemma involves a tabbed navigation that can vary in size depending on the number of tabs added to it. Adjacent to the navigation, there is a second area hous ...

Is there a way to implement the adjacent selector in combination with the :before selector?

Hello there, I am working on a timeline area with a slick effect and have implemented slick.js for that purpose. I am trying to change the color of my spans within the elements. Specifically, I changed the first span in the slick-active class element succe ...