Use CSS Grid to anchor the final element to the right side of a horizontal navigation menu

I am facing an issue with my horizontal navigation bar that contains a dynamic number of links. In this specific case, there are 3 links displayed below:

https://i.sstatic.net/f5vcn.png

My goal is to keep the first two links in their original position and move the third link all the way to the right. I have managed to achieve this by setting a fixed width for the links using

grid-template-columns: repeat(auto-fill, minmax(130px, 1fr));
. Then, I applied grid-column-end: -1; to the element representing the third link.

However, I do not want all the links to have the same width. I would like the widths to be set to auto, but this approach does not allow me to create an implicit grid stretching across the entire width. Consequently, I am unable to place the third link at the extreme right of the navigation bar. Is there a simple way to accomplish this using CSS Grid? If not, how can I achieve it with Flexbox without resorting to floats or absolute positioning?

Below is the current CSS code I am using:

ul.nav {
  display: grid;
  grid-auto-flow: column;
  align-items: center;
  justify-content: start;
  grid-gap: 10px;
  margin: 0;
  padding: 0;
  list-style: none;
}

Answer №1

When using Grid, the rule to follow is: "set all columns to auto regardless of number, but the last column to 1fr". Then apply margin-left: auto to the last grid item.

Currently, the Grid spec (level 1) does not provide a way to target the last column in an unknown number of columns.

To my understanding, achieving this with grid-template-columns, grid-auto-columns, or a combination of both is not possible.

On the other hand, the layout becomes straightforward with flexbox. Simply set margin-left: auto on the last item.


Grid Layout

If you know the exact number of columns, here's how it can be done:

Set the first two columns to auto based on content length.

Assign 1fr to the third column, which:

  1. takes up all available space on the line, and
  2. pins the first two columns to the left.

Finally, use an auto margin to pin the third link (grid item) to the right within the space of the third column.

nav {
  display: grid;
  grid-template-columns: auto auto 1fr;
}

a:last-child {
  margin-left: auto;
}

/* demo styles */
nav { background-color: lightgray ; border: 1px solid gray; padding: 5px 0; }
a   { background-color: lightgreen; border: 1px solid gray; }
<nav>
  <a>Link 1</a>
  <a>Link 2</a>
  <a>Link 3</a>
</nav>

Flex Layout

For a flexible number of flex items, follow these steps:

nav {
  display: flex;
}

a:last-child {
  margin-left: auto;
}

/* demo styles */
nav { background-color: lightgray ; border: 1px solid gray;  padding: 5px 0; }
a   { background-color: lightgreen; border: 1px solid gray; }
<nav>
  <a>Link 1</a>
  <a>Link 2</a>
  <a>Link 3</a>
</nav>

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 steps can I take to ensure that my logos remain visible even when I close the menu and resize the window?

On my website, I have a menu of logos that are clickable. These logos always display except on smaller screens, where they need to be toggled to show using a hamburger menu. The menu toggles fine when it is on a smaller screen, but there is an issue when y ...

Retrieve the browser version of a client using C# (When Internet Explorer Compatibility mode is activated)

Is there a way to retrieve the actual version of the client's browser from C# code? Using Request.Browser or HTTP_USER_AGENT provides details, but in Internet Explorer (IE), when compatibility mode is enabled, it always returns IE 7 regardless of the ...

What is the best way to achieve CSS rounded corners while keeping the border lines sharp?

Currently, I am utilizing the border-radius property to make the corners of a div rounded. In addition, there is a border line at the bottom of the div. Here is an example: <div style="border-radius: .5em; border-bottom: 1px solid black">Content< ...

Generate a loop specifically designed to execute the code following the menu in the script

My website has the code snippet below: let txt_com = document.querySelector(".text_user"); let num_com_user = document.querySelector(".massage_for_user"); txt_com.addEventListener("click", function() { if (this.classList.contains("num_com_user")) { ...

The object of type 'NoneType' does not have the 'next_element' attribute

Here we have an HTML snippet of a website with a single itemprop="brand": <dd itemprop="brand" class="attributeValue-2574930263"> <a class="link-3970392289 link__default-1151936189 attributeLink-2414863004&qu ...

Secure login system featuring self-contained HTML and Javascript functionalities

I want to create an idle game that will save data on the server instead of using cookies. I am looking for a straightforward method (ideally without using MySQL or PHP) to implement user registration and login functionality using HTML5 and/or Javascript. ...

Facing compatibility problems with JavaScript and Cascading Style Sheets in Google Chrome?

Welcome to the site . Let's address a couple of issues with JavaScript and CSS: Firstly, the JS code seems to be malfunctioning only in Chrome, throwing an error that reads: 'Uncaught TypeError: Object [object Object] has no method 'on prij ...

Extract the entire div including all its elements and then transmit it using the PHP mail function

Currently, I am developing a feature that allows users to send an email. The email should include only one div from the page which contains elements added using the jQuery drag and clone function. I am unsure how to copy the entire div along with its child ...

Ways to patiently wait in a for loop until the ajax call is completed

I am a beginner in web development and currently working on a small website project that involves using ajax to display new comments. Below is the function I have created: function show_comments() { $('div#P_all_posts>div').each(function () { ...

The dynamic loading of an HTML/JavaScript input range object within a div is not functioning properly

Hey there, I have a hidden div containing a range input: <div id="hiddencontainer" style="display:none;"> <input id="range1" type="range" min="1" max="10" step="1" name="rating" value="1" onmousemove="showrangevalue()"/> </div> The ...

Leveraging the Xpath Contains function to locate an element with specific text content

For my Selenium Xpath locators, I have always used the Contains function successfully. However, I recently encountered an issue where it does not work for a TD element in a table, despite sending the correct text to the function. To replicate the problem ...

Using input masking to restrict user input to only numbers and English alphabet characters

My input field is masked as "999999999" and functions correctly with an English keyboard. However, I am able to enter Japanese/Chinese characters into it, which breaks the masking. Is there a way to limit input to English keyboard numerics only? <inpu ...

Showing the name of a class

Hello everyone, I have a piece of JavaScript code that generates HTML buttons when the page loads. The button attributes are fetched from a database through an ASP page. Everything is working fine except for displaying the class attribute - it shows as u ...

How can I trigger the second animation for an object that is constantly moving within a specific range in the first animation?

I am looking to create a simulation of rising and falling sea levels. Currently, when I click the button, the level rises from its starting point to the top, but I am unsure how to achieve this effect in my code. Below is the code I have written so far, an ...

Changing the color of an Angular <div> element with scripting

I am currently working on an Angular 6 project and I need to change the colors of a div tag from a script after a click function. However, I also need to change it back to transparent. When I click on the "Inheritance" option, the background color of the ...

Creating a visually appealing multi-bar chart in AngularJS: Tips for effectively presenting data

Imagine that I have the JSON data below: [ { month: "Jan", cost: 80, energy: 90 }, { month: "Feb", cost: 50, energy: 80 }, { month: ...

Internal link formatting using CSS styling

I have a question about formatting links with fonts and colors to make them clickable. I managed to achieve the desired font and color styles using a specific code snippet, but struggled to make the link clickable: <table border="0" cellpadding="1" cel ...

Modify the width measurement from pixels to percentage using JavaScript

Looking for some help with a content slider on my website at this link: . I want to make it responsive so that it adjusts to 100% width. I managed to make it responsive by tweaking some code in the developer tools, but now I'm stuck. The bottom two p ...

JQuery method for extracting a specific span's content from a div

I am faced with extracting specific text from a span within a div element. Below is the code snippet for my Div: '<div class="dvDynamic_' + pid + '"><p hidden="true">'+pid+'</p><span class="count_' + pid ...

Is it possible for the HTML (source code of a web page) to alter once the page is saved onto a local computer?

Upon opening a webpage at http://www.designova.net/rise/index-01.html, I decided to inspect its source code. Afterwards, I saved the page to my computer and opened it in an editor (sublime text 2). To my surprise, I noticed that the HTML content in the two ...