Is it possible to justify align inline-block elements across multiple lines?

I have encountered various scenarios where I need a DIV to contain an inline-block menu element - usually an anchor - and behave as if the elements are vertically justified, even when they overflow onto multiple lines.

Let me illustrate with an example:

Here is my codepen: http://codepen.io/anon/pen/wBRpqJ?editors=110

Output:

When the browser window is resized to a smaller size, the final inline-block Anchor element moves to a new line, as shown in the screenshot (at around 725px width):

Output:

This behavior is acceptable, but what I would like to achieve is to evenly distribute the elements within the DIV across two lines when it exceeds one line, making it appear roughly justified. If you resize the codepen to about 500px wide, you will see how I envision it looking if the elements cannot fit on one line. The image below demonstrates what I aim for in case any line breaking happens within the parent DIV element.

Output:

I understand that achieving perfect equality may not always be possible due to dynamic content and different situations. Still, I aim to justify the elements in such a way that each row in the block accommodates a similar number of elements, give or take 1 for odd counts.

Is this achievable using CSS?

P.S> Since the contents and contexts where this solution might apply vary, specific solutions tailored only to this particular case might not suffice.

Edit: Flexbox has been suggested as a solution; how can Flexbox help achieve the desired outcome?

Edit 2: Criteria -- The menu elements are center-aligned and are individual inline blocks. By trying to justify them all, the center alignment gets disturbed, and additional spacer lines surround the Anchor elements inside the NAV container.

Edit 3: I will include the code used in the codepen example:

CSS:

.mainbox {
        width:90%;
        max-width:1200px;
        min-width:400px;
        margin:0.4em auto;
        font-family: Arial, Helvetica, sans-serif;
        font-size: 1em;
        border: 1px solid #006;
    }

nav {
    background-color: rgba(204,204,204,0.4);
    padding:5px 5px 0px 5px;
    text-align:center;
    position: absolute;
    /* bottom increased from zero to make example clearer on codepen */
  bottom:1em;
    margin:auto;
    width:90%; 
  /* width adjusted from 100% for codepen layout */
}
nav a {
    font-size: 0.9em;
    font-weight: bold;
    text-decoration: none;
    padding:2px 4px;
    color: #000;
    border: 1px solid #000;
    line-height: 1.1em;
    background-color: #DDDDDD;
    margin:0 3px 3px 3px;
    display:inline-block;
}
nav a:hover, nav a:focus {
    background-color: #FFFFFF;
    color:#000000;
    text-decoration: none;
}

HTML:

<div class="mainbox">
  <header>
  <nav>
           <a href="#cal" title="Cottage Availbility">Availability</a>
<a href="#tariff" title="Tariff">Tariff</a>
<a href="#" title="Make A Booking ">Make A Booking</a>
<a href="http://www.website.com/AccessStatement.pdf" title="Access Statement" target="_blank">Access Statement</a>
<a href="http://www.website.com/TandCs.pdf" title="T&amp;Cs" target="_blank">T&amp;Cs</a>
<a href="#contact" title="Contact the owners">Contact</a>
<a href="http://www.elsewhere.co.uk" title="Visit the website">
Parent Site</a>
        </nav>
  </header>
  </div>

Answer №1

If you want to justify the last line of text, you can use the clever :after pseudo element hack. By creating a fake line with :after, you trick the browser into justifying that final line. Remember, traditional justification doesn't apply to the very last line.

.menu {
  margin: 0;
  padding: 0;
  text-align: justify;
  font-size: 0;
}
li {
  display: inline-block;
  font-size: 24px;
  width: auto;
  background-color: #ccc;
  text-align: center;
  padding: 0 10px;
  border: 1px solid black;
  margin:10px;
}
ul:after {
  display: inline-block;
  width: 100%;
  content: '';
}
<ul class="menu">
  <li>Item 12341231</li>
  <li>Item 123462346</li>
  <li>Item 234523</li>
  <li>Item 34563457</li>
  <li>Item 456756</li>
  <li>Item 567856</li>  
  <li>Item 678969</li>
  <li>Item 7453456</li>
  <li>Item 8234523</li>
</ul>

Answer №2

If you want everything to wrap exactly the way you desire, consider utilizing media queries:

@media (max-width: 725px) {
    .parent-container {
        width: 500px;
    }
}

While not flawless, implementing these settings can help achieve the desired wrapping effect.

Answer №3

Here's a clever workaround that utilizes @media to create a line break using a pseudo element.

@media screen and (max-width: 750px) {
    nav span:nth-of-type(4)::after {
        content: "";
        display: table;
        height: 10px;
    }
}

Keep in mind: To implement this solution, I wrapped each <a> with a <span> tag.

Check out the demo: http://jsfiddle.net/s88381hb/1/

Answer №4

Utilizing CSS is one option, however incorporating javascript to reinforce the styling could potentially yield better results

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 best way to style radio boxes in HTML to resemble checkboxes and display X's when selected?

I'm looking to create a form with radio boxes that resemble checkboxes and display a glyphicon x when selected. I've experimented with various solutions such as: input[type="radio"] { -webkit-appearance: checkbox; /* Chrome, ...

I am struggling to make my table adapt to different screen sizes and become

Here is an example of a table: <TABLE class=vysledky > <TR class=podtrzeni> <TD width="39" height="19">Order <br /> League</TD> <TD width="39" height="19">Order <br /> Team</TD> <TD width="3 ...

Creating a dropdown menu within a <span> element with JavaScript

Snippet of HTML: <body onload="init();firstInit();"> Snippet of JavaScript: function init(){ var tb = new Ext.Toolbar({ renderTo: 'toolbar', height: 25 }); var ht='<table><tr>'; ht+='<td>&apo ...

The foundation grid system is experiencing difficulties when implemented on an Angular form

After successfully installing Foundation 6 on my Angular project, I am facing an issue with the grid system not working properly. Despite numerous attempts to troubleshoot and debug, I have not been able to resolve this issue. If anyone has any insights or ...

Guide on how to toggle disabled input text box upon checking checkbox using JavaScript

When the checkbox next to the appended text box is checked, I want to disable that text box. The hard-coded text box is already disabled when its checkbox is checked. You can see the actual outcome by running the code snippet or check out the screenshots b ...

basic two-column design

Located at the end of this page, you will find two distinct columns. On the right side, there is a Twitter feed, while the left side showcases a YouTube video and a comments section. Below is the HTML and CSS code that was used to create these columns: .l ...

After receiving a response from an Ajax call, the forms are reloaded

Experimenting with servlet calls through Ajax functionality using a simple program. A form consisting of a text box and a div with some text. The program takes input from the user, replaces the text inside the div tag. The form looks like this: <form& ...

Display the Ajax response in a designated div

I am facing an issue with my ajax code. It doesn't print any output, but when I use alert() to print the output, it shows up fine. $(".grp-ans").each(function(e){ $.ajax({ type: 'POST', url: 'show-answ ...

Compiling a list of products, but the user interface needs some adjustments

Currently, I have designed a product list menu that includes a hover dropdown feature. This means that when a user hovers over a specific menu item, the corresponding list will automatically appear. However, I am facing two issues with this setup. Firstly, ...

Step-by-step guide on creating a linear graph in CSS using a table

I am a newcomer to the world of CSS and I am looking to create a graph using CSS without the use of any libraries or frameworks. Can someone kindly assist me in drawing a linear graph using this HTML table? Appreciate any help in advance. <html> & ...

"Want to extend the current date (Y-m-d) by a few days? Here

On my form, there is a date input that I want to automatically set to the date that is 14 days from today. I know how to set the value to today's date, but how can I add 14 days to it? <p>Term:<br> <input type="date" name="term" i ...

Is it possible to dynamically adjust div height using on resize event?

In my current setup, I have two separate divs on the left and right sides. The issue arises when the height of the left div exceeds the height of the right div. In such cases, the function adjusts the heights to be equal and hides any excess text in the le ...

Creating adaptable HTML images by specifying width and height attributes within the image tag

My current website setup involves loading a full image and automatically adjusting its size to fit the screen by setting the image width to 100% in CSS. While this method works smoothly, it may not be following standards as I am not specifying width and he ...

What is the method to fetch the index and remove an element from an object in angular 8?

I've been attempting to remove an element from an object, but for some reason it's not getting deleted. The format of my object is as follows: {"UNDET":0,"HLDS":8,"NGS":2,"NGRT":1,"TotalCount":13,"NGX":1} What I'm looking to do now is del ...

Top IDE for web development with HTML5, JavaScript, CSS, and JQuery compatibility, alongside user-friendly GUI design capabilities

Currently, I am working on a project that involves using the RGraph HTML5 canvas package for graph drawing. In addition to this, I also need to create a visually appealing GUI. While experimenting with Netbeans, I found that it lacks the necessary featur ...

Bootstrap 4 Nav Table of Contents with Expand and Collapse Feature

Currently, I am encountering an issue with implementing a button to expand and collapse a "table of contents" in Bootstrap 4. The code I have so far can be viewed here: https://codepen.io/nht910/pen/RwwwyKB Code Snippet: <div class="main-wrapper col- ...

Tabs within the AutoComplete popup in Material-UI

Would it be feasible to showcase the corresponding data in the AutoComplete popover using Tabs? There could be potentially up to three categories of data that match the input value, and my preference would be to present them as tabs. Is there a way to in ...

Using classes to override CSS

I've been going through the Material UI Overrides documentation in an attempt to customize the color of each radio button, but I'm having trouble grasping it conceptually. If I start with Material UI's default setup for radio buttons, how ca ...

Update Bootstrap Vue to change the colors of the breadcrumbs

Struggling to customize the look of bootstrap-vue breadcrumbs? I've attempted various combinations of classes and styles in the breadcrumb and breadcrumb-item tags, but to no avail. Every time, I end up with blue or grey text on a light grey backgroun ...

What is the reason behind the inconsistent behavior of Javascript's Date.getDate() and .setDate() methods?

As a hobbyist coder, I'm facing a challenging problem with building a dynamic HTML/CSS calendar. My goal is to have cells filled in based on today's date. However, when I attempt to add days to fill in another 13 days by looping through HTML elem ...