What is the best way to distribute multiple inline-block elements evenly?

Is it feasible to evenly distribute numerous elements in a div with adjustable width?

Check out this example that doesn't work. While using text-align:center; will center the elements, margin:0 auto; does not have any effect. I am aiming for something like a combination of justify and center:

|..<elem>..<elem>..<elem>..<elem>..|       // for one container width
|..<elem>..<elem>..<elem>..|               // for smaller container width
|....<elem>....<elem>....|                 // even smaller container

The container's size can be adjusted by the user. As the saying goes, a picture paints a thousand words:

Container (red box) width:100%; Therefore, the user has the ability to resize it (either through the browser window or JavaScript).
<--> denotes equal spacing. In the second row, <--> are larger because there is more space available. I managed to replicate this effect using:

text-align:center;
word-spacing:3em;    // although any fixed value will throw off the proportions

Answer №1

I came across a brilliant method that perfectly addresses your query.

In essence, all you have to do is apply text-align:justify; to the container element along with an additional invisible block at the end.

This technique works because inline-block elements are considered part of the text content, essentially representing a single word each.

By utilizing justify, the words in your text will be evenly distributed to fill the entire width of the element with uniform spacing between them. When it comes to inline-block elements, they will also be spaced out uniformly.

The mention of an extra invisible block at the end is crucial due to the fact that standard text-align:justify doesn't justify the last line of text. While this behavior is desired for regular text, aligning inline-block boxes requires all of them to be aligned.

To address this, add an unseen 100% width element at the conclusion of your inline-block elements. This phantom element essentially acts as the final line of text, enabling the justify technique to function correctly for the remaining blocks.

You can employ the :after pseudo-selector to generate the invisible element without necessitating alterations to your markup.

Please refer to the updated version of your jsFiddle provided for a practical demonstration: http://jsfiddle.net/ULQwf/298/

Additionally, the original article elaborating on this concept in greater depth can be found here:

[EDIT] Upon reviewing the image included in your query, I don't have a superior solution but I do possess some supplementary insights that may prove beneficial.

What would ideally resolve your issue is a :last-line selector. This would allow you to apply text-align:justify to the main text while centering the final line using text-align:center.

Regrettably, the lack of a :last-line selector eliminates this possibility, as only :first-line is recognized.

An alternative worth considering is the existence of text-align-last, which could fulfill your requirements:

text-align:justify;
text-align-last:center;

While this solution appears ideal, it is non-standard and possesses limited browser support.

You can explore more about this feature on MDN by following this link: read about here on MDN.

If absolute necessary, despite its partial browser support, this option could cater to some of your users. However, this isn't the most practical approach.

Despite my hopes for a better solution, it seems like this might be as close as you can get. The concept is almost within reach of achieving what you desire but falls slightly short. It's unfortunate because logically, it seems like a reasonable task to undertake.

Answer №2

I have revised your provided example and made adjustments to create a combination of block and inline styling. This is necessary because justify alone only works for inline text.

div{
    width:530px; /* I modified the size of the div to accommodate fixed width */
    border:1px red solid;
    text-align:justify;    /* It will justify 100% of containing div, for centering add another div with % size and centered */

}
div span{ 
    width:60px;
    border:1px yellow solid;
    display:inline-block;  
    position:relative; 
}

div:before{
    content:'';
    display:block;
    width:100%;
}

div:after {
    content:'';
    display:inline-block; 
    width:100%;
}

Answer №3

After experimenting with a new approach, the result in the fiddle appears quite similar to the image provided. The spacing between elements is consistent across both lines, with the elements being alternated.

div{
    width:250px; /* Modified the size of the div to allow for fixed width, unless scrolling is desired */
    border:1px red solid;
    text-align:center;    /* Content will be centered within the containing div, another div can be added for additional centering if needed */
}
div span{ 
    width:60px;
    float:justify;
    border:1px yellow solid;
    display: inline-block; 
    margin-left:2%;
    margin-right:2%;

}

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

Working with AngularJS: binding data to dynamically appended HTML elements using JavaScript

Is there a way to connect an angular event and model to an html element that is added through javascript code? To see my code, click here: https://jsfiddle.net/hq7qk48n/13/ <div ng-app> <div ng-controller="MyController"> <input ...

Activate the preview mode by transmitting information between two controllers

I'm trying to set up a preview mode in one controller to show an image in another controller using an angular service. However, I'm struggling with the final step of getting the URL from the passed parameter into the ng-src in SideMenuCtrl dynami ...

Executing a Firebase JavaScript script on a remote web server client

I have limited experience with Javascript and I am struggling to get my code to execute. I have already completed the Android java portion, but when I attempt to run the html file, nothing happens. I am unsure if there are bugs in my code or if it needs to ...

PHP multiline string using PHP language

I am struggling with echoing a large amount of PHP and HTML code. Despite trying the obvious solutions, I am unable to make it work: <?php echo ' <?php if ( has_post_thumbnail() ) { ?> <div class="gridly-image"><a href="< ...

The FileReader.result is found to be null

Currently, I am in the process of setting up a page that allows users to upload a txt file (specifically a log file generated by another program) and then modify the text as needed. Initially, my goal is to simply console.log the text, but eventually, I pl ...

What is the best way to position a table caption at the top of a table?

I need help setting up a calendar within a table structure, and I'm struggling to add a caption at the top of the table. Unfortunately, I can't modify the current table structure. I want it to resemble the example shown below: https://i.sstatic. ...

What is the best way to align the bottom of the last child of a flex element?

Current: https://i.sstatic.net/e7V8x.png Desired: https://i.sstatic.net/Xszod.png Is it possible to achieve this using the flex or grid model, or do I need to reconsider the structure with a different approach? Below is the code snippet: .sections { ...

How can I implement a recursive nested template call in Angular 2?

Hopefully the title isn't too misleading, but here's my dilemma: I am in the process of building an Angular 2 app and utilizing nested templates in multiple instances. The problem I am facing involves "widgets" within my app that can contain oth ...

Tips for creating a seamless Bootstrap collapse effect

I have noticed a slight flicker in the content collapse when using this code. Is there a way to make it collapse more smoothly? <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> <script ...

Should we avoid styling HTML tags?

Would it be considered poor practice, for instance, to apply the following CSS rules to all images on my webpage in order to make them responsive: img { display: inline-block; height: auto; max-width: 100%; } Instead of using img-responsive on each ...

Retrieving information from emails, yet providing disorganized text fragments

I have developed a method to remove html, style/script tags, and new line tags from the source code of email pages: def extract_message(url): markup = open(url) soup = BeautifulSoup(markup, "html.parser") for script in soup(["script", "style"] ...

What impact does the order of the element I'm specifying in my .css file have on its appearance after being rendered?

(An update has been added below) In my project, I am working with a .css file and an index.html document. The goal is to create a panel of buttons on the screen [to prototype the usability of a touchscreen interface], with each button assigned a specific ...

Centered Layout using HTML and CSS

Exploring the world of Ruby on Rails and HTML has been quite an adventure. Today's question veers away from RoR and focuses on HTML and CSS. As I attempt to center my body, a peculiar issue arises: Help me solve this problem here How can I align the ...

Problem with Bootstrap 5 dropdown menu: Functional on main page, but failing on subpages

As a beginner with Bootstrap, I recently attempted to integrate a dropdown menu into my website by following the Bootstrap documentation (version 5.1) for guidance. While the dropdown menu functions correctly on the homepage, it fails to work properly on ...

Python: Convert a variable to an HTML file

This question may seem simple, but I've been searching for a solution without success for hours. I have an HTML file called "teste.html" I am using jinja 2 to make changes in my HTML. env = Environment(loader=FileSystemLoader('.')) template ...

What happens when there is no match found while attempting to edit a form with the UI-Bootstrap typeahead directive?

Here is the code that demonstrates how my typeahead input box functions. Users can enter a name, and the relevant information will populate the rest of the form. If no match is found, users should still be able to input the name and related details into th ...

"Displaying mongoose date in the HTML5 input type date format (dd/mm/yyyy) is a simple process that can

I have a structured data in MongoDB as shown below: var Person = new Schema({ "Name": { type: String, required: true }, "DOB": { type: Date, "default": Date.now } }); An instance of this schema is created using NodeJs with mongoose ODM: { "N ...

Prevent event propagation in jQuery by using .stopPropagation() when hovering over a

When trying to implement event.stopPropagation() in a specific scenario, I encountered an issue with a blinking background image on my submenu. To address this, I added a pseudo-element (background:green) to the parent element by toggling a new class using ...

Issue with click event for submit button in ASP.Net following a change in dropdown list index using JavaScript

Currently, I have an asp.net application where a confirmation popup alert is displayed when the selected index changes to a specific value ("Cancelled") in a dropdown list. <asp:DropDownList ID="ddlStatus" runat="server" CssClass="selectstyle" DataText ...

JavaScript: Can you clarify the value of this variable using five sets of double quotations?

Could you please review the code snippet below for me? <script type="text/javascript"> function recentpostslist(json) { document.write('<ul class="recommended">'); var i; var j; for (i = 0; i < json.feed.entry.length; i++) { ...