Caught in a dilemma between flex-end and space-between, with margin thrown into the mix

When working with a flexbox and using justify-content:space-between, the first and last items are aligned to the edges of the flex container, with space distributed between them. But how can I align the first item to the right while keeping all other items aligned to the right as well (without filling the entire width)?

The sample code provided below is not ideal because when using flex-end, I have to add margin to the items which causes the first item in each row to not stick to the right edge.

#flexcontainer{
  display: -webkit-flex;
  display: flex;
  flex-wrap:wrap;
  -webkit-flex-direction: row;
  flex-direction: row;
  -webkit-justify-content: flex-end;
  justify-content: flex-end;
  background:#ff8800;
}


.flexitem{
display: -webkit-flex;
display: flex;
margin:20px;
width:24%;
background:#666666;
box-sizing:border-box;
    height:50px;

}
<div id="flexcontainer">
  <div class="flexitem"></div>
  <div class="flexitem"></div>
  <div class="flexitem"></div>
  <div class="flexitem"></div>
  <div class="flexitem"></div>
  <div class="flexitem"></div>
</div>

This approach is also not ideal because the items are not aligned to the right (but rather take up the entire width):

#flexcontainer{
  display: -webkit-flex;
  display: flex;
  flex-wrap:wrap;
  -webkit-flex-direction: row;
  flex-direction: row;
  -webkit-justify-content: space-between;
  justify-content: space-between;
  background:#ff8800;

}


.flexitem{
display: -webkit-flex;
display: flex;
margin:0;
width:24%;
background:#888888;
box-sizing:border-box;
    height:50px;
}
<div id="flexcontainer">
    <div class="flexitem"></div>
    <div class="flexitem"></div>
    <div class="flexitem"></div>
  </div>

My desired layout is depicted in this image (where the first item sticks to the right with no right margin, and the fourth item sticks to the left if there are four elements, while others align to the right for more than four elements): https://i.sstatic.net/dygAV.jpg

Answer №1

From what I know, the optimal way to use a flexbox for achieving your desired layout is by adjusting the flex-basis and margin of the flexitems using the following code:

  margin: 20px;
  display: flex;
  flex: 0 1 calc(25% - 40px);
  1. The flex-basis value of calc(25% - 40px) in the flex style divides the width into four sections while accounting for margins.

  2. Note that I have disabled flex-grow.

  3. Adding flex-end completes the setup.

I'd appreciate your feedback on this approach. Thank you!

#flexcontainer {
  display: flex;
  flex-wrap: wrap;
  flex-direction: row;
  justify-content: flex-end;
  background: #ff8800;
}
.flexitem {
  margin: 20px;
  display: flex;
  flex: 0 1 calc(25% - 40px);
  background: #666666;
  box-sizing: border-box;
  height: 50px;
}
<div id="flexcontainer">
  <div class="flexitem"></div>
  <div class="flexitem"></div>
  <div class="flexitem"></div>
  <div class="flexitem"></div>
  <div class="flexitem"></div>
  <div class="flexitem"></div>
</div>

UPDATE:

I made some additional adjustments to the margin calculations:

  1. Reduced the flex-basis by another 10px to accommodate removing 20px from both ends of each row:

    flex: 0 1 calc(25% - 30px);
    
  2. To ensure the rightmost / leftmost boxes align with the right / left edges:

    .flexitem:nth-child(4n) {
      margin-right: 0;
    }
    .flexitem:nth-child(4n + 1) {
      margin-left: 0;
    }
    .flexitem:last-child {
      margin-right: 0;
    }
    

I would love to hear your thoughts on these modifications. Thank you!

#flexcontainer {
  display: flex;
  flex-wrap: wrap;
  flex-direction: row;
  justify-content: flex-end;
  background: #ff8800;
}
.flexitem {
  margin: 20px;
  display: flex;
  flex: 0 1 calc(25% - 30px);
  background: #666666;
  box-sizing: border-box;
  height: 50px;
}
.flexitem:nth-child(4n) {
  margin-right: 0;
}
.flexitem:nth-child(4n + 1) {
  margin-left: 0;
}
.flexitem:last-child {
  margin-right: 0;
}
<div id="flexcontainer">
  <div class="flexitem"></div>
  <div class="flexitem"></div>
  <div class="flexitem"></div>
  <div class="flexitem"></div>
  <div class="flexitem"></div>
  <div class="flexitem"></div>
</div>

Answer №2

One simple solution could be to eliminate the right margin in your initial example. Would this alteration achieve the desired appearance?

#flexcontainer {
  display: flex;
  flex-wrap: wrap;
  flex-direction: row;
  justify-content: flex-end;
  background: #ff8800;
}


.flexitem {
  margin: 20px;
  margin-right: 0;
  width: 24%;
  background: #666666;
  box-sizing: border-box;
  height: 50px;
}
<div id="flexcontainer">
  <div class="flexitem"></div>
  <div class="flexitem"></div>
  <div class="flexitem"></div>
  <div class="flexitem"></div>
  <div class="flexitem"></div>
  <div class="flexitem"></div>
</div>

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 lasting placeholder text with gaps between each word

Looking to create a unique text input with static content on the right and editable text on the left https://i.stack.imgur.com/K0YfM.png Any suggestions? ...

Turn off automatic vertical scrolling when refreshing thumbnails with scrollIntoView()

My Image Gallery Slider has a feature that uses ScrollIntoView() for its thumbnails, but whenever I scroll up or down the page and a new thumbnail is selected, it brings the entire page back to the location of that thumbnail. Is there a way to turn off t ...

Tips for enabling only a single div to expand when the "read more" button is clicked

I'm having trouble with my blog-style page where I want only one "read more" link to expand while collapsing the others. I've tried various jQuery methods and HTML structures, but haven't been able to achieve the desired result. Can someone ...

What could be causing my CSS style to not take precedence over Bootstrap in this particular case?

I am struggling to make my CSS styles take precedence over Bootstrap's defaults for aligning table headers. Below is the code for my table: <table class="userProjectsTable" id="userLeadProjectsTable"> <tr class="userProjectsHeaderRow" i ...

The CSS3 Border-Radius feature is showing some color bleeding on a border that is colored differently

I designed a dynamic-width container with rounded edges using border-radius, along with a bold border on one side of the container in a different color. Everything looks fine when the browser window is small, but as I expand the window size, I notice the ...

Error: Media queries must always start with a parenthesis

I couldn't sleep because of this issue, guys. Here is a snippet of my problematic code: <style lang="scss" scoped> @import '~/assets/scss/main.scss' .home_nav{ nav { } } </style> The error ...

Highlight text when the user is scrolling the page - using JQUERY

Can anyone suggest a way to dynamically underline text as the user scrolls down a webpage? The underline should only be visible while the user is scrolling. I've experimented with animate.css and other plugins, but haven't been able to achieve th ...

Tips for ensuring your webpage stays current with regular updates through JavaScript

This webpage acts as a dynamic newsboard, constantly updated with the latest data from my Database through an API, all without requiring a page refresh. While the timer solution seemed simple, I am seeking a more resource-efficient approach. I have resear ...

Is there a way to remove the entire row if I dismiss a bootstrap alert?

Hey there! I'm having a little issue with an alert in a row-fluid. Curious to see? Check out my fiddle. So, when I click the "x" button to dismiss the alert, the row is still visible. Any idea how I can make the entire row disappear when I dismiss it? ...

What is the process for extracting a numerical value from a text box and using it to update a database?

Trying to figure out how to add a numerical value entered into a text box to a value in a database table when the submit button is clicked. Let's say there's a table called customers in the database, with columns for name and balance. The goal i ...

After logging in, I am unable to redirect to another PHP page as the login form simply reloads on the same page

Lately, I've encountered an issue that has persisted for a few days. The login validation is functioning flawlessly. However, the problem arises when attempting to redirect to another page, specifically 'index.php', after logging in. Instead ...

CSS3 animations and transitions offer dynamic and engaging effects for websites

Could CSS3 animations be utilized for scrolling a window? In jQuery, you would typically use something like: $(window).animate({scrollTop: '+=200'}, 300, function() { }); Therefore, my inquiry is whether it is feasible to achieve a similar effe ...

What is the most effective way to align a thumb to the left and content to the right?

What is considered the optimal method for positioning an image to the left with two text fields to the right of it? Is using floats or positioning better? <li> <a href=""> <img src=""THUMB HERE /> </a> <a href=""> TITLE </ ...

The vertical lines separating the buttons are not evenly centered

I need help to center a vertical line between my buttons in the middle of the header. Currently, the line goes up and my disconnect button is not aligned properly. Can you assist me in creating a responsive design? Thank you. https://i.sstatic.net/XIeiQ4E ...

Window backdrop being filled

I am attempting to set a background image that fills the entire window regardless of its size. I have implemented html, css and script as shown below: // Function adaptImage() // Parameters: targetimg function adaptImage(targetimg) { var wheight = $ ...

"Function.click operates successfully when no arguments are given, but encounters issues when arguments are supplied

I had a function that was functioning correctly: $('#buttFurniture').click(onFilterCLick); However, when I decided to pass arguments to the function, it stopped working: $('#buttFurniture').click(onFilterCLick(arrOutput, arrFurniture ...

Browsers seem to only respond to the FileReader onload event on the second try

Currently I am working on implementing in-browser image processing using HTML5 and encountering a strange issue specifically in Chrome. The problem lies with the onload event handler for the File API FileReader class, as the file is only processed correctl ...

Class name that changes the cursor to a pointer shape in CSS

My question is: Are there any CSS classes or attributes in Bootstrap 4 specifically designed for applying the pointer: cursor property to buttons or links? <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" rel= ...

Links in words not redirecting to asp.net documents

I have a collection of Word files that require hyperlinks. These hyperlinks lead to an htm file with an anchor, however the htm file is not accessible directly via a URL for security purposes. Instead, it links to an ashx handler file which fetches the f ...

Guiding the jQuery Document

I currently have a stylesheet in the head section with the following content: *, body { direction:rtl; } Upon inspection, I found that the dir variable of jQuery is set to ltr: $(function(){ alert(this.dir); }); How can I obtain the specific page di ...