The issue of CSS Flexbox not aligning items to the right

Having trouble with the flexbox and need assistance setting up my navbar.

I've written some code to display my logo + title on the left side of the navbar, and a menu of options on the right. However, all items are aligning to the left and the item--4 is not floating over to the right. Any insights?

.flex-container {
  background: #eee;
  display: flex;
}

.flex-item {
  background: orangered;
  color: white;
}

.flex-item--4 {
  flex-grow: 1;
  margin-left: auto;
  background: purple;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="583a37372c2b2c2a3928186c766e7669">[email protected]</a>/dist/js/bootstrap.min.js"></script>

<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="84e6ebebf0f7f0f6e5f4c4b0aab2aab5">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet" />
<nav class="navbar navbar-expand-md navbar-dark bg-dark fixed-top">
  <div class="flex-container">
    <div class="flex-item">
      <a class="navbar-brand" style="padding-left: 20px;" href="{% if user.is_staff or user.is_superuser %}{% url 'admin:index' %}{% else %}{% url 'app:home' %}{% endif %}">
        <img src="{% static 'img/bootstrap-solid.svg' %}" width="21" height="21" alt="Logo" class="mr-2 mt-n1"> Title
      </a>
    </div>
    <div class="flex-item--4">
      <div class="collapse navbar-collapse" id="navbarNavDarkDropdown">
        <ul class="navbar-nav">
          <li class="nav-item dropdown">
            <a class="nav-link dropdown-toggle" href="#" id="navbarDarkDropdownMenuLink" role="button" data-bs-toggle="dropdown" aria-expanded="false">
                        Hello {{ request.user.get_full_name|default:request.user }}!
                        </a>
                <ul class="dropdown-menu dropdown-menu-dark" aria-labelledby="navbarDarkDropdownMenuLink">
                    <li><a class="dropdown-item" href="#">About</a></li>
                    <li><a class="dropdown-item" href="#">Account</a></li>
                    <li><a class="dropdown-item" href="#">Settings</a></li>
                    <li>
                        <hr class="dropdown-divider">
                    </li>
                    <li><a class="dropdown-item" href="{% url 'account:logout' %}"> Sign Out</a></li>
                </ul>
          </li>
        </ul>
      </div>
    </div>
  </div>
</nav>

Answer №1

By applying flex-grow: 1 to the flex-item--4 element, it will expand to occupy all available space, leaving no room for margins.

If you remove flex-grow: 1, the element will be pushed towards the right side of the container.

In addition, I found it necessary to include width:100% in the flex-container. I suspect this adjustment was needed due to a style constraint from Bootstrap.

.flex-container {
  background: #eee;
  display: flex;
  width: 100%;
}

.flex-item {
  background: orangered;
  color: white;
}

.flex-item--4 {
  margin-left: auto;
  background: purple;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f89a97978c8b8c8a9988b8ccd6ced6c9">[email protected]</a>/dist/js/bootstrap.min.js"></script>

<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6f0d00001b1c1b1d0e1f2f5b4159415e">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet" />
<nav class="navbar navbar-expand-md navbar-dark bg-dark fixed-top">
  <div class="flex-container">
    <div class="flex-item">
      <a class="navbar-brand" style="padding-left: 20px;" href="{% if user.is_staff or user.is_superuser %}{% url 'admin:index' %}{% else %}{% url 'app:home' %}{% endif %}">
        <img src="{% static 'img/bootstrap-solid.svg' %}" width="21" height="21" alt="Logo" class="mr-2 mt-n1"> Title
      </a>
    </div>
    <div class="flex-item--4">
      <div class="collapse navbar-collapse show" id="navbarNavDarkDropdown">
        <ul class="navbar-nav">
          <li class="nav-item dropdown">
            <a class="nav-link dropdown-toggle" href="#" id="navbarDarkDropdownMenuLink" role="button" data-bs-toggle="dropdown" aria-expanded="false">
                        Hello {{ request.user.get_full_name|default:request.user }}!
                        </a>
            <ul class="dropdown-menu dropdown-menu-dark" aria-labelledby="navbarDarkDropdownMenuLink">
              <li><a class="dropdown-item" href="#">About</a></li>
              <li><a class="dropdown-item" href="#">Account</a></li>
              <li><a class="dropdown-item" href="#">Settings</a></li>
              <li>
                <hr class="dropdown-divider">
              </li>
              <li><a class="dropdown-item" href="{% url 'account:logout' %}"> Sign Out</a></li>
            </ul>
          </li>
        </ul>
      </div>
    </div>
  </div>
</nav>

Answer №2

To make it full width, include width: 100%; and add flex-grow: 0 to the menu to prevent it from filling the remaining space and align it to the right. The existing margin-auto: left already achieves the right alignment.

.flex-container {
  background: #eee;
  display: flex;
  width: 100%;
}

.flex-item {
  background: orangered;
  color: white;
}

.flex-item--4 {
  flex-grow: 0;
  margin-left: auto;
  background: purple;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="73111c1c07000701120333475d455d42">[email protected]</a>/dist/js/bootstrap.min.js"></script>

<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d8bab7b7acabacaab9a898ecf6eef6e9">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet" />
<nav class="navbar navbar-expand-md navbar-dark bg-dark fixed-top">
  <div class="flex-container">
    <div class="flex-item">
      <a class="navbar-brand" style="padding-left: 20px;" href="{% if user.is_staff or user.is_superuser %}{% url 'admin:index' %}{% else %}{% url 'app:home' %}{% endif %}">
        <img src="{% static 'img/bootstrap-solid.svg' %}" width="21" height="21" alt="Logo" class="mr-2 mt-n1"> Title
      </a>
    </div>
    <div class="flex-item--4">
      <div class="collapse navbar-collapse" id="navbarNavDarkDropdown">
        <ul class="navbar-nav">
          <li class="nav-item dropdown">
            <a class="nav-link dropdown-toggle" href="#" id="navbarDarkDropdownMenuLink" role="button" data-bs-toggle="dropdown" aria-expanded="false">
                        Hello {{ request.user.get_full_name|default:request.user }}!
                        </a>
            <ul class="dropdown-menu dropdown-menu-dark" aria-labelledby="navbarDarkDropdownMenuLink">
              <li><a class="dropdown-item" href="#">About</a></li>
              <li><a class="dropdown-item" href="#">Account</a></li>
              <li><a class="dropdown-item" href="#">Settings</a></li>
              <li>
                <hr class="dropdown-divider">
              </li>
              <li><a class="dropdown-item" href="{% url 'account:logout' %}"> Sign Out</a></li>
            </ul>
          </li>
        </ul>
      </div>
    </div>
  </div>
</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

Adjusting data points on a radar chart.js through user interaction

I have a radar map generated using chart.js, along with some input fields where users can enter values that I want to reflect in the graph. I am exploring ways to update the chart dynamically as the user types in the values. One option is to have the char ...

How can CSS3 be used to target the initial or final visible element in a selection?

Looking to style form fieldsets with margins, while removing the margin-top for the first non-hidden fieldset and margin-bottom for the last non-hidden fieldset (any fieldset can be dynamically set as hidden by a script). I attempted the CSS below without ...

Using FEWER loops to create column classes on Twitter - What is their functionality?

Bootstrap utilizes various LESS mixins to create its column classes, along with other classes; .make-grid-columns() { // Common styles for all sizes of grid columns, widths 1-12 .col(@index) when (@index = 1) { // initial @item: ~".col-xs-@{index} ...

just half of the four $_POST variables are actually assigned

Here is a simple form structure: <table class='table table-striped table-bordered table-hover' id='dataTables-example'> <thead> <tr> <th>1</th> <th>2</th> ...

Apply a red border to any form inputs that contain incorrect information when the submit

How can I add red borders to my form inputs only when they are invalid after submission, without displaying the red borders from the start? Currently, I am using the input:invalid selectors in CSS, but this causes the red borders to appear immediately. I ...

Arranging card images in a row using semantic cards for optimal alignment

Trying to create a row of semantic-ui cards with images at the top, I ran into an issue with varying image heights causing different card title positions. The goal is to have all images be the same height while still adapting to larger screens. Although I ...

Showing information retrieved from a database using PHP in a sequential manner

I'm currently working on developing a webpage that features 6 rows of images, with each row containing 4 images accompanied by captions right below them. The structure I have in mind is as follows: IMAGE IMAGE IMAGE IMAGE TEXT TEXT TEXT TEXT IMAGE ...

Using jQuery to activate classes on navigation pill elements

I'm currently developing a website and using a nav-pills setup with bootstrap 4. I am trying to implement an active state on click for two links that trigger accordions to display content. Below is the jQuery code I am using: $(function () { $("#filt ...

How can I adjust a large image to fit the browser window using CSS?

I have a large image (3000px by 2000px) that I want to use as the background for my website and adjust it to fit the window size. Currently, I have implemented the following CSS: body { background: url('image.jpg') !important; background ...

What steps can I take to use CSS to disable a webpage?

Is there a way to create a disabled web page using CSS where users cannot click on any content and only view the content below the screen? ...

Is there a way to customize the font size of Material UI Autocomplete?

I'm currently trying to customize the Material UI Autocomplete component with my own CSS. Specifically, I aim to adjust the font size of the input field. Below is my current implementation: <Autocomplete style={{ width: 200, height: 60, ...

Issue with rvest's html_table() function causing it to return -Inf when the maximum value

Recently, I've been working on scraping tables from websites and I'm currently trying to extract a table from . After some research, I found that using the rvest library along with the html_table() function worked best for me. In fact, I successf ...

What are some creative ways to customize the background of a MaterialUI modal design?

I am currently facing an issue with my MUI Modal setup. The backdrop is displaying as black even though I have proper styling in place. No matter what I do, the backdrop remains pitch black and does not update. Below is the code snippet along with a scree ...

"Rearranging the Firefox ghost image by dragging and dropping it

My drag and drop game is working perfectly on all browsers except for Firefox. In Firefox, the ghost image that appears when an item is dragged seems to be positioned very far away from the cursor. Although the ghost image can still be seen on the page, it ...

Revamping the back button functionality to redirect to a different location

As I face a situation where I need to modify the browsing history dynamically, consider this scenario: I am currently on my page: http://mysite.example.com and then I navigate to another page by clicking a link: http://mysite.example.com/sports Upon clic ...

Vertical scroll through a list of columns with a stationary header, while allowing both the list and the header to

Check out this JSFiddle example: https://jsfiddle.net/jefftg/1chmyppm/ The layout currently has orange header columns and white list rows that scroll together horizontally. However, the goal is to have the white list rows scroll vertically while keeping t ...

What is the best way to showcase nested array information from a JSON file on an HTML webpage?

students.json { "students": [ { "studentname": "Rohit Kumar", "grade": "A", "student": [ { "SNo": "1", "Subject": "Maths", "Concept": "Numbers" }, { "SNo": "2", ...

Obtain the rotational value in 3D CSS using JavaScript by extracting it from the matrix3d()

My element has been 3D transformed in the following way: .foo { transform: rotateX(-30deg) rotateY(35deg); } Now, I am looking to retrieve these values using JavaScript. Extracting the 3D matrix is simple: var matrix = $('.foo').css('tr ...

The live feature is operational, but unfortunately the on feature is not functioning

I am facing an issue in my code where replacing .live with .on is not working. I have been trying to identify the problem but haven't found a solution yet. $(document).ready(function () { /* Reading the data from XML file*/ $.ajax({ ...

What is the best way for me to collect messages submitted through a form on my website?

After completing my website using HTML, CSS, and JavaScript, I added a form with inputs for name, email, and message at the bottom of the page. Now, I am trying to figure out how to receive the information submitted by visitors in my email. ...