Align a collection of images in a grid format on the center of the page with

I am trying to center a div that contains multiple 145px X 145px thumbnail images without setting a fixed width. The goal is to have as many images in each row as the browser window can fit. However, I want to keep the images left-aligned within the centered div. Using text-align: center won't work because it centers the entire row, including any leftover images in the last row. Is there a way to achieve this using CSS alone, or would JavaScript be necessary?

You can view my example on jsbin here: http://jsbin.com/eTukegu/3/edit

(Please note that I have used 7 thumbnail placeholder divs for demonstration purposes)

<div id="thumbnail_container">
  <div class="thumbnail"></div>
  <div class="thumbnail"></div>
  <div class="thumbnail"></div>
  <div class="thumbnail"></div>
  <div class="thumbnail"></div>
  <div class="thumbnail"></div>
  <div class="thumbnail"></div>
</div>

CSS:

#thumbnail_container
{
  margin: 5px;
  padding: 0;
}

.thumbnail
{
  width: 145px;
  height: 145px;
  background-color: #fff;
  display: inline-block;
  margin: 5px 1px 1px 5px;
  padding: 0;
}

Answer №1

Applying display:table with adjustments to the left and right margins:

#image_holder{
 display: table;
 margin: 10px auto;
 padding: 0;
}

Answer №2

Here's the javascript code I came up with to handle this specific issue: (the size of each thumbnail image is set at 145x145 pixels, with a 10px margin between each)

window.onload = function()
{
    adjustThumbnailWidth();
};

window.onresize = function ()
{
    adjustThumbnailWidth();
};

function adjustThumbnailWidth()
{
    var containerWrapper = document.getElementById('thumbnail_container_wrapper');
    var containerWrapperWidth = containerWrapper.offsetWidth;
    var boxesInRow = Math.floor((containerWrapperWidth - 10) / 155);
    var newWidth = boxesInRow * 155;
    var container = document.getElementById('thumbnail_container');
    container.style.width = newWidth + "px";
}

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

When async/await is employed, the execution does not follow a specific order

I'm curious about the execution of async/await in JavaScript. Here are some example codes: async function firstMethod(){ new Promise((resolve, reject)) => { setTimeout(() => { resolve("test1"); }, 3000); }); } async ...

What is the best method for aligning forms vertically within a page layout?

I'm working on designing a contact form, but I'm having trouble getting everything to align properly. Specifically, I can't seem to get the form elements to line up vertically and I also want the Message label to appear on the top left side ...

What is the solution for fixing scrolling while keeping the header fixed and ensuring that the widths of headers and cells are equal?

Is there a way to set a minimum width for headers in a table and provide a scroll option if the total width exceeds 100% of the table width? Additionally, how can we ensure that the width of the header and td elements are equal? Below is the HTML code: ht ...

Converting Callbacks to Promises in Node.js

I am facing a challenge with my node js application as I am attempting to promisify multiple callback functions without success. It has reached a point where I am unsure if it is even feasible. If you can assist me in promisifying the code provided below, ...

There are two different ways to set a hyperlink in HTML. One method is by using the href attribute, where you provide the URL inside the quotation marks. The other

While browsing, I stumbled upon this interesting piece of JavaScript code: onClick="self.location.href='http://stackoverflow.com/'" I incorporated this code into my website, and it seems to have the same effect as using the href attribute. Sin ...

Should all pages in React be rendered on the server side?

Currently, I rely on Next.js for implementing server-side rendering on my React website. At the moment, I have implemented server-side rendering across almost all pages of the site, including profile information and other content that requires a login to ...

I'm currently leveraging Vue.js and Python Flask for my backend development. I'm looking to establish some local variables. What is the best way to accomplish this?

Here is my Vue js file where I am utilizing two URLs from localhost. My goal is to create a configuration file that will allow me to make changes in one place and have those changes reflected throughout. <template> <div> <div class="glob ...

Do not include any null or empty objects when assigning to an array in Mongoose

When using mongoose's find() or findOne() methods, the returned value will be [] and null, respectively, if the where conditions are not met. This can cause issues when assigning these values to an array. Currently, I am filtering out the null values ...

Tips for obtaining the state of a local variable in a Vue method:

How do I access the state of a local variable within a method in Vue? I am looking to set a specific value for the dialog in order to open the popUp. After loading the data, my goal is to open the popUp by using this porting method. import { mapState, m ...

Do not need to refresh the form

I developed a PHP-based Feedback form that includes a Popup from Foundation 5. <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <style type="text/css"> .auto-style1 { margin-left: 1px; ...

Challenges arise when using two side-by divs with a 100% height

Caution: This page may include NSFW images. I am attempting to set the left div to a width of 300px and have the right one fill the remaining space on the page. After finally getting them to sit side by side, I encountered some strange height issues due ...

Displaying a collection of items using Rails, implementing form_for and integrating Ajax functionality

Looking to display a list of "Interests" for users to "follow" by clicking on a button linked to the Interest's image. Once the follow button is clicked, the Interest and its image should be removed from the list. Attempting to use a hide function in ...

Utilize the Webstorm debugger in conjunction with node.js for seamless debugging

Several weeks ago, I attempted to get the webstorm debugger up and running, but unfortunately, it didn't work. Now, I'm giving it another shot, but I'm faced with the same outcome. I am following the instructions outlined here: http://www.j ...

Adding a character at the beginning of each loop iteration in a nested array with Vue.js

When working inside a v-for loop, I am attempting to add a character at the beginning of each item in a nested array that may contain multiple items. I have explored various options but have not been successful: :data-filter="addDot(item.buttonFilter ...

Pass information submitted through a JavaScript prompt to an expressjs endpoint

I'm currently facing a challenge in extracting the value from my prompt in order to modify a category using a JavaScript function. Typically, I would rely on a form to pass variables to the request.body, but that's not an option here. This is wh ...

Using jquery to dynamically change audio source on click

Is there a way to dynamically change the audio src using jquery? <audio id="audio" controls="" > <source src="" type="audio/mpeg" /> </audio> <ul id="playlist"> <?php if($lists) { foreach ($lists as $list) { ?> ...

Dealing with query strings within routeprovider or exploring alternative solutions

Dealing with query strings such as (index.php?comment=hello) in routeprovider configuration in angularjs can be achieved by following the example below: Example: angular.module('app', ['ngRoute']) .config(function($routeProvider, $loc ...

Angular and Node.js Integration: Compiling Files into a Single File

I have a question, is it possible to include multiple require js files in one file? If so, how can I create objects from them? Calling 'new AllPages.OnePage()' doesn't seem to work. To provide some context, I'm looking for something sim ...

Having issues with @react-three/drei in next.js environment

Having trouble using drei materials and other features like MeshWobbleMaterial, MeshDistortMaterial, or ContactShadows? You may encounter errors such as: react-three-fiber.esm.js:1383 Uncaught TypeError: Cannot read property 'getState' of null a ...

Unable to retrieve Vuex state within a function

Currently, I am developing a Laravel+Vue application where Vuex is used for state management. While working on form validation, everything seems to be progressing smoothly except for one particular issue that has me stuck. The problem arises when I attempt ...