Align elements evenly across the center while maintaining a controlled distance between each one

In my current scenario, I am working with a flexible number of elements ranging from 2 to 5. My goal is to evenly distribute these elements within a div that also has variable width. This task might seem straightforward, but there's a unique twist involved. I want to limit the horizontal spacing between each element to a maximum value. This means that even if the div is wide and only a few elements are present, I do not want them spread out across the entire width. Instead, I prefer to center them in the div. Here's an example of what I aim to achieve:

Narrow div, 5 elements:
[   1  2  3  4  5  ]
Wide div, 3 elements:
[          1  2  3         ]

Below is my initial attempt at solving this issue, starting with the HTML structure:

<div id="nav5">
    <ul>
        <li>[1]</li>
        <li>[2]</li>
        <li>[3]</li>
        <li>[4]</li>
        <li>[5]</li>
        <ul>
</div>
<div id="nav3">
    <ul>
        <li>[1]</li>
        <li>[2]</li>
        <li>[3]</li>
        <ul>
</div>
<div id="nav2">
    <ul>
        <li>[1]</li>
        <li>[2]</li>
        <ul>
</div>

Now, let's move on to the CSS styling:

li {
    float: left;
    font-size: 22px;
    font-weight: bold;
    max-width: 80px;
}
#nav5 li {
    width: 20%;
}
#nav3 li {
    width: 33.333%;
}
#nav2 li {
    width: 50%;
}
ul {
    text-align: center;
    overflow: auto;
    width: 100%;
}
div {
    width: 100%;
    max-width: 320px;
    margin: 0 auto;
    text-align: center;
    background-color: lightgray;
}

If you'd like to see a live demonstration, check out this Fiddle link: http://jsfiddle.net/jmy690bq/

While the current implementation is close to what I envisioned, it falls short in keeping the elements centered. Additionally, manually specifying the widths of li items is not ideal. An automatic solution would be more efficient. Although using JavaScript is an option, I prefer finding a CSS-only approach.

Answer №1

If you're looking to create a flexible layout, consider using flexboxes:

.nav {
  display: flex;           /* Begin magic */
  justify-content: center; /* Center the children */
}
.nav > li {
  flex-grow: 1;            /* Allow them to grow if there is extra space */
  max-width: 80px;         /* Set a maximum width for each item */
  text-align: center;      /* Center the content within each item */
}

.nav {
  display: flex;
  justify-content: center;
  max-width: 320px;
  background-color: #D3D3D3;
  list-style: none;
  margin: 0;
  padding: 0;
}
.nav > li {
  flex-grow: 1;
  max-width: 80px;
  text-align: center;
}
<ul class="nav">
  <li>[1]</li>
  <li>[2]</li>
  <li>[3]</li>
  <li>[4]</li>
  <li>[5]</li>
</ul>
<ul class="nav">
  <li>[1]</li>
  <li>[2]</li>
  <li>[3]</li>
</ul>
<ul class="nav">
  <li>[1]</li>
  <li>[2]</li>
</ul>

Answer №2

li {
    display: inline-block;
    font-size: 22px;
    font-weight: bold;
}

li + li {
    margin-left: 2em; //for illustration purposes
}

ul {
    text-align: center;
    overflow: auto;
    width: 100%;
}

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

Creating a dynamic hover drop-down navigation bar in ASP.NET

After successfully creating a navigation bar with hover effects, I am now looking to implement a dropdown list when hovering over the items. Can anyone provide guidance on how to achieve this? Below is the current code snippet I am working with: <ul c ...

Storing user-provided image files in Laravel: A comprehensive guide

I am facing an issue with a file insert box in my HTML file. The code looks like this: <input id="image" type="file" name="image" value="{{ old('image') }}" accept="image/gif, image/jpeg, image/png& ...

How to apply gradient colors to borders using CSS

Is it possible to create a simple border bottom color with a gradient effect? div{ border-bottom:10px solid linear-gradient(#FF4000, transparent); height:20px; width:auto; background:#ccc; } <div></div> ...

Add a border to the 'contenteditable' class in a Bootstrap table after it has been modified

Looking for help with JavaScript and jQuery! I have a script that creates an HTML table from a CSV file, using Bootstrap for styling. I want to add CSS or a border to a table cell after it has been edited, but my jQuery attempts haven't worked. Any su ...

What is the process for attaching a right ribbon label onto a card in Fomantic UI components?

I am completely new to Fomantic (and web development in general) and I'm attempting to create a website featuring a card with a ribbon label on the right side. I saw similar designs in the documentation where they used a segment instead. However, when ...

Data containing visual content is not being successfully transferred to the MySQL database

I am having an issue where the code is not sending data to the database after clicking on submit. I have also attempted using the POST method with no success. These are the table names in my database: id (AI), image, name, dob, fathername, fatheroccu ...

Is there a way to substitute all underscores in HTML tag IDs and classes with a hyphen symbol?

I recently realized that I used underscores instead of hyphens in some of my CSS class and id names. To correct this, I want to replace all underscores with hyphens using the sublime text replace feature (ctrl + H). Is there a way to change underscores to ...

Making the dropdown width of the shiny selectInput customizable

Inspired by a discussion on Stack Overflow, this code snippet prevents dropdown text wrapping and sets the width for all dropdowns. Is it possible to individually adjust the width of each dropdown created with selectInput? library(shiny) ui <- (fluid ...

Unique Custom Resources like CSS and JavaScript are used to ensure a consistent appearance across all applications

We have identified a challenge where we aim to develop custom CSS, Javascripts and other resources to maintain consistent look and feel across all our applications. These applications could be built using GWT, Thingworx, JSP, etc., and may differ in natur ...

Ways to revamp the overall aesthetic of the entire project

Is there a way to change the colors of all elements in a project when a user checks a checkbox, without having to add a class to each element? Perhaps using a service or a different method? ...

Refresh the options in a dropdown menu after selecting a radio button using jQuery

Upon selecting either the male or female radio button, I wish to populate a list with names corresponding to the selected gender from a database. The male and female tables in the database consist of two columns: {id} and {name}. <?php include "co ...

What is the best way to extract the value from a text box that is being looped through using the post method in order to insert it into

I was working with the code below. Each textbox for attendance is looped a certain number of times, and I need to capture the value of each attendance when the form is submitted to insert the values into a database. <form method="post" action="insert. ...

What is the process for eliminating the hover effect on a Bootstrap button?

I have customized a Bootstrap button in my stylesheet to make it dark, but it still has a hover effect from Bootstrap that I want to remove. How can I get rid of this hover effect? Take a look at the code snippet below for reference: .btn-dark { min-w ...

Troubleshooting the issue of Bootstrap 4 scrollspy failing to update active navbar items

I have been working on a Bootstrap 4.0 landing page and trying to implement ScrollSpy without success. The active menu items are not changing as expected. Here is the code snippet from index.html: <body> <!-- Navbar --> <nav id="main-nav" ...

The list in the navbar is misaligned and not centered vertically within the flex container

I've been working with flex for a while now, but I'm struggling to vertically align the content of my navbar to the center in the code. <nav className="nav navbar"> <h3> Logo </h3> <ul className= &q ...

Programme for Server Login

After creating my own server, I attempted to implement a login feature to restrict access to its files. Unfortunately, using Javascript for this task proved to be insecure as usernames and passwords could easily be viewed in the source code: <form name ...

A method for setting values independently of [(ngModel)] within an *ngFor loop and selecting an HTML tag

I am encountering an issue with [(ngModel)], as it is syncing all my selections to the same variable. My variable is selectStations = []; Therefore, when I choose an option in one select element, it updates all select elements to have the same selected o ...

Is there a way I can link a variable to a URL for an image?

Creating v-chip objects with dynamic variable names and images is causing an issue. The image source string depends on the name provided, but when I bind the name to the source string, the image fails to load. Despite trying solutions from a similar questi ...

Issue with scrolling to the bottom of collapsed sections in Bootstrap

I have a bootstrap collapse panel and I've added a toggle link at the bottom to allow users to expand and collapse the content with a click. The Issue My problem arises when the menu expands, causing it to scroll all the way to the bottom of the pag ...

What is the best way to display a div based on a keyword match?

If the keyword search results in a match, I can display the corresponding input text and its related category div. Now, I am attempting to also search through category names. If the searched keyword matches a category name, that specific div should be visi ...