Maximizing the number of divs arranged horizontally in HTML while utilizing the full line width

My website consists of several fixed-width div elements that are styled to flow inline using the display type inline-block. This layout creates empty space at the end of the line where subsequent div elements cannot be accommodated and have to wrap to the next line.

Is there a way for me to expand all the divs on the row evenly to fill up the row, similar to how text alignment is justified?

In essence, I wish to establish a minimum width on the div elements, fit as many as possible in a single row, and completely fill the entire row.

Below is a snippet of the HTML code I'm working with:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
    <style>
        #container { margin: 100px; padding: 10px; border: 1px solid blue; }
        .item { margin: 10px; width: 300px; min-width: 300px; display: inline-block; border: 1px solid red; }
    </style>
</head>
<body>
    <div id="container">
        <div class="item">Item One</div>
        <div class="item">Item Two</div>
        <div class="item">Item Three</div>
        <div class="item">Item Four</div>
    </div>
</body>
</html>

Can this layout be achieved solely with CSS and HTML or would a script be required?


UPDATE: It's important to note that percentage widths have been suggested to span items along a single row, but that's not the objective here. The goal is to emulate justified text behavior with blocks, even when the number of items varies significantly.

The blocks should maintain uniform size, possess a default (minimum) width for wrapping if necessary, and extend their width to occupy the container's width by filling it with child items.


UPDATE 2:

The current setup yields output akin to this:

|--------------------------- Container -----------------------------|
| |------ 1 ------| |------ 2 ------| |------ 3 ------|             |
| |------ 4 ------| |------ 5 ------| |------ 6 ------|             |
| |------ 7 ------|                                                 |

The desired outcome, however, resembles either one of these layouts:

|---------------------------- Container ----------------------------|
| |-------- 1 --------| |-------- 2 --------| |-------- 3 --------| |
| |-------- 4 --------| |-------- 5 --------| |-------- 6 --------| |
| |-------- 7 --------|                                             |
|---------------------------- Container ----------------------------|
| |-------- 1 --------| |-------- 2 --------| |-------- 3 --------| |
| |-------- 4 --------| |-------- 5 --------| |-------- 6 --------| |
| |------------------------------ 7 ------------------------------| |

Each item possesses a minimum size, so within the above illustration, items #4 and #7 exceed the remaining space on the line and consequently revert to the next line. Ideally, the items already aligned on the line should substantiate the vacuous areas.

Considerations should be given to the potential resizing of the container owing to browser alterations. Therefore, should it diminish to permit only two items per row, the layout should adapt accordingly:

|----------------- Container -----------------|
| |-------- 1 --------| |-------- 2 --------| |
| |-------- 3 --------| |-------- 4 --------| |
| |-------- 5 --------| |-------- 6 --------| |
| |------------------- 7 -------------------| |

This elucidates the fundamental intent behind the query.

Answer №1

If you want to achieve this layout, one way is by utilizing the flexbox model. However, there are some issues associated with it.

There exist an old and a new version of the flexbox model which can make implementation a bit complex. Presently, only Chrome and Opera fully support the new model, while other browsers offer "Partial support". This may mean that they are supporting either older versions of the specifications or syntax, or they haven't fully implemented any flexbox model yet.

I have managed to create something functional using available tools that works in Chrome 26, Safari 5.1.7, IE10, IE9 mode, and IE8 mode. Unfortunately, Firefox version 20 does not support it. It seems like even older versions of Firefox might experience difficulties, as mentioned in the link provided about the lack of flex-wrap property support in Firefox.

The flex-wrap property is crucial for enabling multi-line layouts in most modern browsers. Firefox recently started supporting this property from version 28 onwards. You can check out the details in the provided links.

To view a comprehensive example of how this can be achieved using CSS and HTML, refer to the jsFiddle near the end of the post. For better cross-browser compatibility, a JavaScript solution might be necessary. One option could be modifying existing scripts like FlexieJS to handle older browser versions appropriately.

In conclusion, creating a workaround for outdated browser limitations may require custom JavaScript solutions. The development community is continually working on polyfills and alternative methods to address such challenges, so keep an eye out for updates and reach out for assistance if needed.

The CSS styling code snippet provided outlines various properties required for different browsers to render the layout correctly:

#container {
  /* CSS declarations for container element */
}

.item {
  /* CSS declarations for child items within the container */
}

Answer №2

There are two ways to accomplish this (assuming you know the number of .items):

Method One: Floating the .items is effective, as shown in this fiddle http://jsfiddle.net/David_Knowles/wh5bP/

#container { 
    margin: 100px; 
    overflow:hidden;
    border: 1px solid blue; 
}
.item { 
    width: 23%; /* important: (100% / numberOfItems - margin%) */
    margin: 0 1%; /* important */
    float:left; /* important */
    -moz-box-sizing: border-box; /* only needed to compensate for the border used in your debugging */
    -webkit-box-sizing: border-box; 
    box-sizing: border-box;
    border: 1px solid red; 

}

Method Two:

Inline-block elements are affected by white space between line breaks. Ensure there are no spaces between the .items. See example here: http://jsfiddle.net/David_Knowles/wh5bP/1/

<div id="container">
    <div class="item">Item One</div><div class="item">Item Two</div><div class="item">Item Three</div><div class="item">Item Four</div>
</div>

.item { 
    width: 23%;
    margin: 0 1%;
    display:inline-block;
    -moz-box-sizing: border-box;
    -webkit-box-sizing: border-box; 
    box-sizing: border-box;
    border: 1px solid red; 

}

If the number of .items is unknown, consider using the flexbox model. http://css-tricks.com/using-flexbox/ http://caniuse.com/flexbox

If your audience uses IE9 or older versions, a polyfill like Flexie can be utilized.

Answer №3

If you're looking to utilize Flexbox for layout, keep in mind that you'll need a fallback for non-Flexbox compatible browsers. Centering your content might be the most reliable approach.

Check out this example on CodePen: http://codepen.io/cimmanon/pen/lBDwu

ul {
  display: -webkit-flexbox;
  display: -ms-flexbox;
  display: -webkit-flex;
  -webkit-flex-wrap: wrap;
  -ms-flex-wrap: wrap;
  flex-wrap: wrap;
  list-style: none;
  padding: 0;
  text-align: center;
}

@supports (flex-wrap: wrap) {
  ul {
    display: flex;
  }
}

li {
  display: inline-block;
  -webkit-flex: 1 0;
  -ms-flex: 1 0;
  flex: 1 0;
  min-width: 10em;
  background: #CCC;
  border: 1px solid;
  margin: .5em;
}

Note that Chrome, Opera, and IE10 are among the few browsers that support flex wrapping. Others will fall back to an alternative layout.

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

Looking to duplicate the elements with the click of a button?

I am in need of assistance with my registration form. My goal is to move the elements contained within the <fieldset> tags to the end of a row when the user clicks the + button. The result you see initially has been recreated. Thank you for your s ...

Can I set a nested DIV to a higher z-index than a parent DIV in IE7, so that it appears above it?

UPDATE!!! Apologies for the confusion, it turns out the issue was with the #container DIV missing "float:left;". Please check the HTML rendering in Firefox and IE7 to see the impact! I am facing difficulty getting a nested DIV to appear above another nes ...

Scraping using Regex to extract form_ids with varying values but identical names

Is there a way to extract the value of a form id from an HTML page using either regex or xpath, specifically focusing on scraping the value from the second instance of the form_id name? Any suggestions on the most effective method to accomplish this using ...

Inspect Element - base tag href URL for inline CSS allocation

When utilizing the <base> tag in HTML along with the <style> tag on Microsoft's Edge Browser, I encounter a peculiar issue. Here is a very basic example: <!DOCTYPE html> <html lang="en"> <head> <title>Edge de ...

Creating a flexible grid layout with DIVs that share equal width dimensions

Struggling with my HTML and CSS code, I need a way to structure nested DIV blocks into a responsive grid where each block has the same width. Despite my efforts, nothing seems to work as expected. Currently, the nested DIVs are stacked vertically one on to ...

Customize the appearance of the date input box in MUI KeyboardDatePicker

Currently, I am attempting to customize the appearance of the KeyboardDatePicker component including board color, size, font, and padding. However, none of the methods I have tried seem to be effective. Here is what I have attempted so far: 1 . Utilizing ...

Use a JavaScript function on identical IDs

Can someone please help me figure out how to hide multiple divs with the same id using JavaScript? I attempted the following: <script> function filterfunc() { if(document.getElementById('filter_deductible').value == 'id_50'){ ...

The current_time() function displayed an incorrect time value

When I utilized the current_time() function in PHP to retrieve the current time, it displayed an incorrect time. Instead of the correct time, it is showing 12 hours and 30 minutes earlier than the actual current time, even after modifying the php.ini file ...

Ways to transition to an iframe window

I am having difficulty selecting an iframe popup window as it is not coming into focus. Below is the image of the popup window along with the button I am attempting to click: https://i.stack.imgur.com/VzkOX.png This is the code snippet that I have been ...

Show the most recent image from a folder in real-time

Looking for a solution to automatically display the latest image from a folder without refreshing the page? Check out this code snippet that achieves just that: <?php foreach (glob('/home/pi/camera/*.jpg') as $f) { $list[] = $f; } sort( ...

Gradually vanishing words while they glide across the screen

I want to achieve a similar effect seen in the game A Dark Room. The text in the game serves two purposes which I am trying to replicate: The new text is added above the old text instead of below it, pushing the older text down the page as the game progr ...

Unable to adjust the size of the font within a text field component in Material UI

I'm currently delving into learning Material UI and am faced with the task of enlarging the text field on my webpage. Despite embedding styles along with the field, the height, width, and other properties change except for the size. Here's the sn ...

How can I output HTML code using php echo without using quotation marks?

My issue involves printing out HTML code that is not stored as a simple string, requiring me to decode it before echoing. The problem arises when I echo the decoded value and unwanted quotes appear, disrupting the output. Here's an example: <div> ...

Three.js is failing to render within a specified div

My current project involves utilizing three.js to create a cube rendering. Despite the cube appearing on the screen, I am facing issues with getting it to display within the specified div element and in the desired style. HTML: <div id="render"> & ...

Issues with the FacebookConnect plugin on PhoneGap Build

Just getting started with PhoneGap build and attempting to create a simple app with a Facebook login button. The documentation for PhoneGap build makes it seem easy to add this plugin. index.html <!DOCTYPE html> <html> <head> <met ...

Is there a way to automatically select all checkboxes when I select contacts in my case using Ionic 2?

initializeSelection() { for (var i = 0; i < this.groupedContacts.length; i++) { for(var j = 0; j < this.groupedContacts[i].length; j++) this.groupedContacts[i][j].selected = this.selectedAll; } } evaluateSelectionStatus() { ...

I am looking to expand my CSS/HTML menu with an additional sub-sub menu. What is the correct way to achieve this?

This is my current CSS code that I am working on. I am trying to create a multi-level menu in Blogger with submenus, sub-submenus, and sub-sub-submenus without disrupting the existing formatting. .top-nav { background-color: #f9f9f9; background: t ...

What is the best method for starting a string using the symbol '~'?

Hello everyone! I have a task that requires me to add a special feature. The user needs to enter something in a field, and if it starts with the tilde (~), all subsequent entries should be enclosed in a frame within the same field or displayed in a list ...

Fixing a div at the top post scroll - bug on iOS mobile device

I am looking to achieve a similar effect as demonstrated in the example below: https://css-tricks.com/scroll-fix-content/ Essentially, the goal is to have a div become fixed at the top of the page after scrolling to a certain point. Initially, the div wil ...

How to make QWebView background translucent

My goal is to make the background of a QWebView element transparent. +---------------------------+ | x | Window title | <<< Hidden borders and title bar +---------------------------+ view->setWindowFlags(Qt::FramelessWindowHint); | ...