The bottom row of elements is aligned to the left in a grid that is centered

Within a div with text-align:center, I have multiple same-size blocks set to display:inline-block.

|        _____   _____   _____   _____       |
|       |     | |     | |     | |     |      |
|       |  1  | |  2  | |  3  | |  4  |      |
|       |_____| |_____| |_____| |_____|      |
|        _____   _____   _____   _____       |
|       |     | |     | |     | |     |      |
|       |  5  | |  6  | |  7  | |  8  |      |
|       |_____| |_____| |_____| |_____|      |
|                                            |

These blocks align horizontally and adjust to new rows as the browser window is resized. To maintain center alignment with the last row left-aligned, the layout should look like this:

|        _____   _____   _____        |
|       |     | |     | |     |       |
|       |  1  | |  2  | |  3  |       |
|       |_____| |_____| |_____|       |
|        _____   _____   _____        |
|       |     | |     | |     |       |
|       |  4  | |  5  | |  6  |       |
|       |_____| |_____| |_____|       |
|        _____   _____                |
|       |     | |     |               |
|       |  7  | |  8  |               |
|       |_____| |_____|               |
|                                     |

However, the current issue is that the last row does not align as intended:

|        _____   _____   _____        |
|       |     | |     | |     |       |
|       |  1  | |  2  | |  3  |       |
|       |_____| |_____| |_____|       |
|        _____   _____   _____        |
|       |     | |     | |     |       |
|       |  4  | |  5  | |  6  |       |
|       |_____| |_____| |_____|       |
|            _____   _____            |
|           |     | |     |           |
|           |  7  | |  8  |           |
|           |_____| |_____|           |
|                                     |

It is crucial that the center alignment is maintained regardless of the number of columns. The solution should not involve adding filler divs or styling individual blocks. The layout must adapt dynamically without relying on a fixed number of blocks or rows.

Here is a reference pen for demonstration:

http://codepen.io/anon/pen/IDsxn

Is there a possible solution that doesn't rely on flexbox, considering support for older browsers like IE9? If a JavaScript solution is the only option, I would like to explore that as well.

Similar questions have been asked, but none have provided a comprehensive explanation:

How to align left last row/line in multiple line flexbox

CSS - Left align the last row of images in a centered div

Fix centering last line of elements in fluid container grid to be left aligned while container stays centered

Center multiple inline blocks with CSS and align the last row to the left

Answer №1

Implementing an Adaptive Grid with Display Inline-Block

This flexible grid design offers a simple solution: minimal markup and CSS, making it easier to integrate into a live website and customize to fit specific requirements.

=>> SEE DEMO HERE <<= (resize the window to observe the effect)


html, body {
    margin:0;
    padding:0;
}
#container{
    font-size:0;
    margin:0 auto;
    width:1000px;
}
.block {
    font-size:20px;
    width: 150px;
    height: 150px;
    margin:25px;
    background: gold;
    display:inline-block;
}

@media screen and (max-width: 430px) {
    #container{
        width:200px;
    }
}
...

Key features of this technique include:

  1. Usage of 4 media queries to adjust block sizes to 200px widths and the container width to 1000px. Depending on your layout and container width, more or fewer media queries may be necessary.

  2. Elimination of white spaces between inline-block elements by manipulating font size. Other techniques can also be used as discussed here.

  3. Consistent fixed margins applied between blocks for spacing.

The number of blocks in one row adjusts based on the container width, maintaining default left alignment for the final items.


Implementation of Floats with Adaptive Margins for Blocks and Container

=>> VIEW DEMO HERE <<= (resize window under 750px to see effect)


html, body {
    margin:0;
    padding:0;
    min-width:150px;
}
.wrap {
    float:left;
    position:relative;
}
.foto {
    width: 150px;
    height: 150px;
    background: gold;
    position:absolute;
}
...

This technique includes:

  1. Utilization of floats
  2. Application of position:absolute;
  3. Usage of :nth-child() CSS selector
  4. Integration of media queries

Blocks are centered within the container with consistent margins around all sides. The design adjusts the block layout based on window width, aligning the final row to the left.

The number of blocks in a row changes according to the window width.

Answer №2

Just a heads up: It is currently 2017 and the grid layout module now provides this functionality right out of the box

* {
    margin:0;
    padding:0;
}

.container {
  display: grid;
  grid-template-columns: repeat(auto-fill, 100px);
  grid-gap: 10px;
  justify-content: center;
  align-content: flex-start;
  margin: 0 auto;
  text-align: center;
  margin-top: 10px;
}
.block {
  background-color: #ddd;
  border: 1px solid #999;
  height: 100px;
  width: 100px;
}
<div class="container">
  <div class="block">Foo</div>
  <div class="block">Foo</div>
  <div class="block">Foo</div>
  <div class="block">Foo</div>
  <div class="block">Foo</div>
  <div class="block">Foo</div>
  <div class="block">Foo</div>
  <div class="block">Foo</div>
  <div class="block">Foo</div>
  <div class="block">Foo</div>
  <div class="block">Foo</div>
  <div class="block">Foo</div>
  <div class="block">Foo</div>
  <div class="block">Foo</div>
  <div class="block">Foo</div>
  <div class="block">Foo</div>
  <div class="block">Foo</div>
  <div class="block">Foo</div>
  <div class="block">Foo</div>
  <div class="block">Foo</div>
  <div class="block">Foo</div>
  <div class="block">Foo</div>
  <div class="block">Foo</div>
</div>

(Check out the Codepen demo).

If the browser support is suitable for your needs, then utilizing grid is the way to go. If not, keep reading....


Like mentioned in @Web-tiki's response, utilizing CSS with a series of media queries is the most effective approach.

However, if you are working with a preprocessor such as LESS, handling this task becomes less daunting and error-prone. (though the CSS may still end up being long and unattractive)

UPDATED CODEPEN (Resize the window to see the results)

This is how you can leverage LESS to configure the media queries:

Begin by setting up some less variables based on the design requirements:

@item-width:100px;
@item-height:100px;
@marginV: 4px;
@marginH: 2px;
@min-cols:2;
@max-cols:9; //establish an upper limit for the number of columns to write media queries for

Then:

Create an iteration mixin as follows: (You can paste this code into )

.loopingClass (@index-width) when (@index-width <= @item-width * @max-cols) {
    @media (min-width:@index-width) {
        .container{
            width: @index-width;
        }
    }

    .loopingClass(@index-width + @item-width + 2*@marginH);
}

.loopingClass (@item-width * @min-cols + @min-cols*@marginH*2);

The mixin provided above will generate a sequence of media queries such as:

@media (min-width: 208px) {
  .container {
    width: 208px;
  }
}
@media (min-width: 312px) {
  .container {
    width: 312px;
  }
}
@media (min-width: 416px) {
  .container {
    width: 416px;
  }
}
@media (min-width: 520px) {
  .container {
    width: 520px;
  }
}
@media (min-width: 624px) {
  .container {
    width: 624px;
  }
}
@media (min-width: 728px) {
  .container {
    width: 728px;
  }
}
@media (min-width: 832px) {
  .container {
    width: 832px;
  }
}

Along with the remaining CSS (LESS):

.container {
  margin: 0 auto;
  text-align: center;
  overflow: auto;
    min-width: @min-cols * @item-width;
    max-width: @max-cols * @item-width;
    display: block;
    list-style:none;
}
.block {
  background-color: #ddd;
  border:1px solid #999;
  box-sizing:border-box;
  float: left;
  height: @item-height;
  width: @item-width;
  margin:@marginV @marginH;
}

... and you achieve the desired outcome.

...and the best part is how easy it is to customize the layout:

You simply need to tweak the variables used in the LESS mixin to align with your preferences - resulting in your exact desired layout.

Answer №3

Check out this straightforward solution using JavaScript and CSS modifications:

http://jsfiddle.net/ha68t/

Tested and functioning properly.

CSS:

.container {
  margin: 0 auto;
  max-width:960px;
  background-color: gold;
}

.block {
  background-color: #ddd;
  border:1px solid #999;
  display: block;
  float: left;
  height: 100px;
  margin: 4px 2px;
  width: 100px;
}

JavaScript:

$(document).ready(function(){
    setContainerWidth();
});

$(window).resize(function(){
   setContainerWidth();
});

function setContainerWidth()
{
    $('.container').css('width', 'auto'); //reset
    var windowWidth = $(document).width();
    var blockWidth = $('.block').outerWidth(true);
    var maxBoxPerRow = Math.floor(windowWidth / blockWidth);
    $('.container').width(maxBoxPerRow * blockWidth);
}

Make sure you have jQuery installed :)

Answer №4

After experimenting with flexbox, incorporating pseudo elements, adding an extra div, and overcoming numerous challenges, I successfully created a grid layout without the need for media queries. This was essential for me as I had to place my grid within various differently sized elements.

One thing to note is that the gutters between items are fluid.

Here is a demo showcasing the implementation: http://codepen.io/anon/pen/OXvxEW

CSS:

.wrapper {
    display: flex;
    flex-wrap: wrap;
    border: 2px solid #ffc0cb;
    max-width: 1100px;
    margin: 0.5rem auto;
    justify-content: center;
}

.wrapper:after {
    content: ' ';
    flex: 1;
    height: 100%;
    border: 1px solid #00f;
    margin: 0.5rem;
}

.child {
    flex: 1;
    border: 2px solid #ffa500;
    min-width: 300px;
    margin: 0.5rem;
    text-align: center;
}

.child-contents {
    width: 300px;
    border: 2px solid #008000;
    height: 100px;
    margin: 0 auto;
}

HTML:

<div class='wrapper'>
    <div class='child'>
        <div class='child-contents'></div>
    </div>
    <div class='child'>
        <div class='child-contents'></div>
    </div>
    <div class='child'>
        <div class='child-contents'></div>
    </div>

    ...etc., more .child's...

</div>

The final output resembles the image provided, where the green rectangles represent divs. The pink/orange borders act as a visual aid to show the layout structure. Removing these borders will result in the desired grid layout (although note that the gutters are fluid).

https://i.sstatic.net/0s6jT.png

Answer №5

Give this simple CSS a try:

CSS:

.row{text-align:center;font-size:0;} .block{text-align:center;display:inline-block;width:150px;height:15px;margin:5px; border:1px solid #dddddd;font-size:13px;}

HTML:

<div class="row">
  <div class="block"></div> 
</div>

.row{text-align:center;font-size:0;}
    .block{text-align:center;display:inline-block;width:150px;height:150px;margin:5px; border:1px solid #dddddd;font-size:13px;line-height:150px;}
<div class="row">
      <div class="block">1</div> 
      <div class="block">2</div> 
      <div class="block">3</div> 
      <div class="block">4</div> 
      <div class="block">5</div> 
      <div class="block">6</div> 
      <div class="block">7</div> 
      <div class="block">8</div> 
    </div>

Answer №6

Up to now, the most effective solution for this issue is using the

CSS Grid Layout Module (View demo on Codepen)

Essentially, the code needed for this can be simplified to the following:

ul {
  display: grid; /* (1) */
  grid-template-columns: repeat(auto-fill, 120px); /* (2) */
  grid-gap: 1rem; /* (3) */
  justify-content: center; /* (4) */
  align-content: flex-start; /* (5) */
}

1) Convert the container element into a grid container

2) Define the grid with an 'auto' number of columns of 120px width. (Use auto-fill for responsive designs).

3) Specify gaps/margins for the grid rows and columns.

4) and 5) - Functions similarly to flexbox.

body {
  margin: 0;
}
ul {
  display: grid;
  grid-template-columns: repeat(auto-fill, 120px);
  grid-gap: 1rem;
  justify-content: center;
  align-content: flex-start;
  
  /* additional properties: */
  list-style: none;
  width: 90vw;
  height: 90vh;
  margin: 2vh auto;
  border: 5px solid green;
  padding: 0;
  overflow: auto;
}
li {
  background: tomato;
  height: 120px;
}
<ul>
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
  <li>5</li>
  <li>6</li>
  <li>7</li>
  <li>8</li>
  <li>9</li>
  <li>10</li>
</ul>

Codepen demo (Resize window to observe the effect)


Browser Compatibility - Check Caniuse

Currently supported by Chrome (Blink) and Firefox, with limited support from IE and Edge (Refer to this article by Rachel Andrew)


For more information on CSS grids:

Answer №7

Implement flexbox for layout:

.container {
  display: -webkit-flex;
   display: flex;
   -webkit-flex-direction: row; 
   flex-direction: row;
   -webkit-justify-content: flex-start;
   justify-content: flex-start;
   flex-wrap:wrap;
}

.block {
  background-color: #ddd;
  border:1px solid #999;
  display: inline-block;
  height: 100px;
  margin: 4px 2px;
  width: 100px;
}

Changes applied successfully.

Answer №8

Your issue does not have a standard solution, only various workarounds are available.

The problem arises when your block container fills up all available space and pushes inner blocks to the next line, causing overflow. This behavior is consistent even with other configurations such as floating. The rendering process is always space-hungry, calculating inner elements based on available space.

Possibly, future advancements in Flexboxes may address this issue, although I have not delved into the complete specifications. It's just a thought...

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 are the steps to add SVG effects to an image or div element?

Embarking on my first venture into using SVG graphics has left me feeling a bit bewildered. Despite extensive research, I have yet to stumble upon the answer to my current quandary. The objective at hand is to transform an image, assuming that the source ...

Customized Bootstrap Dropdown with the ability to add text dynamically

I am working on a Bootstrap dropdown menu that allows users to generate expressions by clicking on the menu items. For example, when the "Action" item is clicked, it should insert {{Action}} into the textbox. The user can then type something like "Hello" a ...

Connecting Documents and Organizing Folders

Currently, I am immersed in a web project leveraging java/ jsp/ servlets/ html/ css within Eclipse Tomcat. At the core of this project, all files are nestled neatly within the WebContent folder. Within my jsp files, I have encountered an issue when trying ...

Internet Explorer is having issues displaying CSS text accurately, particularly in relation to the background-

Having an issue with Internet Explorer not displaying my background clipped text correctly. In other browsers like Chrome and Firefox, the code renders fine: https://i.stack.imgur.com/x9lio.png However, in IE it appears differently: Your code: HTML: & ...

Eliminate spacing between divs of varying heights

I'm facing an issue with my small gallery of images. Despite having the same width, they vary in height causing the second row to start below the tallest image from the previous row. How can I eliminate these empty spaces while still maintaining the v ...

What is the best way to adjust inline svg to the user viewport size?

After working on integrating my interactive SVG maps into my HTML pages, I encountered a minor issue: when inserting my inline SVG into a standard, non-responsive HTML document, it automatically adjusts itself to fit nicely within the user's viewport. ...

Video tag with centered image

For a current project, I am in need of rendering a centered image (a play button) at runtime on top of a video based on the UserAgent. If the userAgent is not Firefox, I want to display the image as Firefox has its own playEvent and button on top of the vi ...

What steps do I need to follow to change the background color to white for the <App/> component in solid-js?

In my solid-js application styled with tailwindcss, I established a gray color in the index.css for the background of various screens. However, I wanted the main <App/> component to have a white background instead. To achieve this, I created an App.c ...

"Customizing the Material-ui TextField DOM Element: A Step-by-Step

After trying the code below, I was expecting to see a yellowish "Hi," but instead received [object Object]. Is there a way to correct this issue? Possibly utilizing InputProps would help, but I haven't been able to locate a comprehensive tutorial on ...

When the web browser page is zoomed out (Ctrl -), elements do not appear to float

Can you test resizing the window to the minimum (CTRL-)? Here's the link: http://jsfiddle.net/Zty9k/13/ This is the HTML code: <ul> <li><img src="http://i.imgur.com/PBuDAFH.gif"></li> <li><img src="http://i.i ...

Tips for aligning a pseudoElement in the center below a bootstrap navigation link

Hello, I'm trying to align the line under my menu that was created using a pseudo element. Here is the HTML code: .nav-link.active { color: #482683; font-size: 14px; } .nav-link.active::after { content: ''; display: b ...

CSS3 translate3D causing input element glitches on Android Webkit

I am encountering some challenges with the Input element in a Webkit Android application that I am currently working on. While testing on version 2.X, it seems that version 3.x does not exhibit these same issues... The structure of the app involves indivi ...

vue-router: A guide to disabling the outline property of the CSS in router-link

I am having trouble disabling the outline of a css link element. I successfully disabled the outline of a regular link using a css class, but I am unable to do so with the <router-link> element. How can I disable the outline for this? .page-link, .p ...

Animating Jquery to smoothly change opacity until it reaches 100% visibility

The script I have does several things, but the main issue lies in the last line where the opacity of the class doesn't seem to reach 100%.... $('.fa-briefcase').parent().on('click', function () { $("#colorscreen").remove(); ...

Difficulty in centering certain elements using Bootstrap

I have recently constructed an element for a webpage within the site I am developing. The item is complete, but I am struggling to center it on the page properly. While I can easily center the image, the text associated with it refuses to budge. Here is t ...

What is the best way to toggle dropdown menu items using jQuery?

Upon clicking on an li, the dropdown menu associated with it slides down. If another adjacent li is clicked, its drop down menu will slide down while the previous one slides back up. However, if I click on the same li to open and close it, the drop down m ...

Using Bootstrap 4, you can create nested rows that will automatically expand to fill their parent container, which in turn has been set

In my current setup, I have a div with the class "d-flex flex-column" that contains a navbar and a container. Within this container, there is another div with the class "d-flex flex-column" which then contains two rows. I am using flex-grow to make the con ...

"Adjusting the width of columns in a Datatable

I have arranged a data table with multiple rows and columns, and I am seeking guidance on how to increase the width of the "Tel. 1, Tel. 2, and Fecha" columns to ensure that the text appears on a single line. I've attempted adjusting the s width and t ...

Is there a way for me to implement this code to achieve the functionality shown in the demo link

$('select').change(function() { var sum = 0; var sum = parseInt($('select[name="bathrooms"]').val() * 25) + parseInt($('select[name="bedrooms"]').val() * 8); $("#sum").html(sum); }); <script src="https://ajax.googleap ...

Align watermark content to the far left side

Having trouble getting my watermark to align properly on the left side of my website's main content. Here is how it currently looks: https://i.sstatic.net/Nfhh5.png The issue arises when I resize the screen or switch to mobile view, as the watermark ...