What is the best way to position a grid of divs in the center?

To elaborate on the issue in depth, I need to establish a few assumptions:

  1. I possess a list of items with an unknown length (can range from 1 to 50 or more).
  2. My objective is to exhibit these items in a grid format, where the number of items per row varies based on the user's display resolution.
  3. Each item has a fixed width of 250px.
  4. The spacing between items should adapt either according to the display resolution or by shrinking the container's width.
  5. I explicitly do not wish to utilize JavaScript for this task.

A prime example showcasing exactly what I aim to achieve can be observed on FoodGawker. Even when transitioning between two different resolution monitors, the layout adjusts seamlessly by accommodating additional items while retaining symmetry and central alignment without relying on JavaScript.

Although I am certain it can be accomplished, the precise method remains elusive to me.

Despite experimenting with various properties such as float: and display:, my attempts have failed to yield the desired outcome.

The code snippet provided below resembles my current progress - its effectiveness is evident with just two inner divs; however, upon incorporating multiple divs, the alignment becomes inconsistent. Any insights on refining this structure would be greatly appreciated.

.center_wrapper {
    background: grey;
    padding: 10px;
    text-align: left;
    overflow: hidden; 
    display:inline-block;
}

.cards_wrapper {
    background: red;
    overflow: hidden; 
    margin-left: auto;
    margin-right: auto;
    text-align: center;
    width: 90%;

}
.card {
    background: blue;
    width: 250px;
    height: 250px;
    margin: auto 20px;
    display:inline;
}


<div class="cards_wrapper">
    <div class="center_wrapper">
        <div class="card">
            <img src="./Index - My ASP.NET MVC Application_files/noImageAvailable.png">
        </div>
        <div class="card">
            <img src="./Index - My ASP.NET MVC Application_files/noImageAvailable.png">
        </div>
    </div>
</div>

Answer №1

Try using inline-block and a % margin

Check out this demo: http://jsfiddle.net/MadLittleMods/9SZDC/

.block
{
    display: -moz-inline-stack;
    display: inline-block;
    vertical-align: top;
    zoom: 1;
    *display: inline;

    width: 250px;
    height: 100px;
    background: #aaeeff;

    margin: 1%;
}​

To center the blocks, you can add text-align to the container

.container
{
    text-align: center;
}

Answer №2

Take out the text-align: left; that is included in the .center_wrapper style to solve the issue.

You can view an example of this fix here.

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

What is the most effective way to assign multiple functions to the onClick event of a button, based on a specific property,

I have a special button that generates a specific type of code when rendered: <button>{this.props.text}</button> This button is named ButtonCustom. In the render method of the main container, I am trying to achieve the following: function my ...

Does "th:each" assign all attributes to the same column?

Having an issue where the "openhours" from the database are loaded into a view, but all 7 opening hours are listed in the Monday column. Below is the code snippet: (HTML) <div class="table-hover"> <table class="table table-striped table ...

How about showcasing bigger images in the main body of the page?

When it comes to using CSS sprites for images, the typical advice is to reserve it for smaller images like icons. Why should larger content images only be represented through <img> elements? Are there not benefits to utilizing spriting for all types ...

TinyMCE file multimedia upload feature allows users to easily add audio, video

I am looking to enhance the functionality of my TinyMCE Editor by enabling file uploads for audio/video and images. Although image uploading is functioning properly, I am encountering issues with other types of files. Despite setting up pickers throughout, ...

Checking for correct format of date in DD/MM/YYYY using javascript

My JavaScript code is not validating the date properly in my XHTML form. It keeps flagging every date as invalid. Can someone help me figure out what I'm missing? Any assistance would be greatly appreciated. Thank you! function validateForm(form) { ...

Is there a way to trigger validation with a disabled property?

My form element is set up like this: <input type="text" id="country" formControlName="Country" /> The form group looks like this: this.myForm = this.formbuilder.group({ 'Country': [{ value: this.user.Country, disabled: this.SomeProperty= ...

The tooltip feature for icon buttons within Material UI list items is not functioning properly as anticipated

Just starting out with Material UI and React, I've encountered a strange UI problem that I can't quite figure out. Hopefully someone here can help me identify what I did wrong. My Approach: I have a List in my code where each list item has butto ...

Having trouble accessing an element using jQuery(idOfElement) with a variable as the name parameter

Possible Duplicate: Issue with JavaScript accessing JSF component using ID Whenever I attempt to retrieve an element by passing a variable in jQuery(idOfElement), it doesn't work. But if I use something like jQuery('#e'), it works perfe ...

Dealing with unreadable strings when formatting dates in a JSP

When working on a JSP project, I encountered a situation where I needed to format a Java Date retrieved from the request. My current approach looks like this: <fmt:formatDate value="${attribute.value}" pattern="yyyy-MM-dd HH:mm:ss"/> This method wo ...

Extracting and retrieving data using JavaScript from a URL

After reviewing some code, I am interested in implementing a similar structure. The original code snippet looks like this: htmlItems += '<li><a href="show-feed.html?url=' + items[i].url + '">' + items[i].name + '& ...

What's the best way to rearrange Bootstrap cards from a horizontal layout to a vertical layout for improved responsiveness?

I'm currently working with Bootstrap to align two cards horizontally, but I also want to ensure that mobile users can view the cards stacked in a column layout. I've experimented with adding 'flex-direction' in combination with the @med ...

Send an array of data from the view to the Controller in CodeIgniter

I have been searching for a solution to this question. However, for some reason, my code is not functioning properly. Here is what I want to achieve: Data Array -> ajax post -> codeigniter controller(save data in DB and redirect to another page) ...

Learn how to hide a bar after clicking the "I agree" button with the help of Bootstrap

click here to see imageIs there a way to make that bar disappear once the user clicks "I agree"? I've searched through Bootstrap documentation but couldn't find a solution. Please assist. Below is the code snippet: <div id="cookie-message" cl ...

Clicking within the text activates the dropdown menu, but clicking outside the text does not

My custom drop down menu is not functioning properly. When I click on the text, it successfully links to another place, but when I click beside the text, it does not link. Can you please help me identify what's wrong here? Your assistance would be gre ...

Aligning three hyperlinks evenly to spread across the webpage

My professor provided the class with an image that may resemble something he could ask us to recreate on an upcoming exam. He suggested we try replicating it at home to study. I have most of it figured out, but there are three links positioned perfectly ac ...

Transforming a canvas element into an image sans the use of toDataURL or toBlob

Recently, I developed a small tool which involves adding a canvas element to the DOM. Strangely, when trying to use toBlob or toDataURL, I encountered an issue with the canvas being tainted and received the error message (specifically in chromium): Uncaugh ...

Are you experiencing issues with the .submit() function when used in conjunction with other

Currently, I am working on a survey form that incorporates JQuery to dynamically display or hide fields based on user selections. //FORM CONDITIONALS: This script is responsible for hiding all the helpfulness radios and only displaying them when "Yes" fo ...

Having trouble with a basic select tag and options not functioning properly in Chrome browser

I encountered an issue where I am unable to expand a simple select tag in Chrome. <select id="filterCategory" class=""> <option>1</option> <option>2</option> <option>3</option> <option>4</option ...

Prevent clicking until the IE 10 and 9 windows have fully loaded

My goal is to prevent clicking on an image element until all the resources have finished loading, enabling the click only after the window.load() or when document.readystate reaches complete status. While this code works well in Chrome and Safari, I am fac ...

SCSS files scattered throughout Solution Explorer create disorder in Visual Studio

I currently work with Visual Studio 2013. Typically, in the solution explorer, scss files are displayed with their .css, .css.map, and .min.css files neatly grouped under the main .scss file. However, I'm experiencing a lack of organization as all th ...