What is the best way to align the middle element of a flex row in the center?

Desired Outcome:

I have three elements within a container styled with display: flex. My goal is to align the left item to the left, the right item to the right, and have the middle item centered.

space-between does not achieve this look due to the varying widths of the elements. Even with differing widths, I want the center element to remain centered.

To resolve this, one could use a wrapper with flex: 1 on the wrappers for each element. However, in my specific case, I am unable to utilize wrappers.

.parentContainer {
  display: flex;
  justify-content: center;
  align-items: center;
}

.parentContainer > *{
   background: red;
   text-align: center;
}
<div class="parentContainer">
 <div class="left">small</div>
 <div class="middle">medium element here</div>
 <div class="right">longer element is here too</div>
</div>

Answer №1

To create this particular layout, the recommended approach involves utilizing flex: 1 on the items because of its cleanliness and validity. While this method is detailed in a post referenced below, it is not applicable to the current question.

  • Centering the middle item while side items have varying widths

Another technique utilizes CSS absolute positioning:

.parentContainer {
  display: flex;
  justify-content: space-between;
  position: relative;
}

.middle {
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
}

/* non-essential decorative styles */
.parentContainer > * { background: orange; text-align: center; padding: 5px; }
p { text-align: center;}
p > span { background-color: aqua; padding: 5px; }
P > span:first-child { font-size: 1.5em; }
<div class="parentContainer">
  <div class="left">small</div>
  <div class="middle">medium element here</div>
  <div class="right">longer element is here too</div>
</div>
<p>
  <span>&uarr;</span><br>
  <span>true center</span>
</p>

This alternative method is elaborated upon in the subsequent posts:

  • Techniques for Aligning Flex Items along the Main Axis (refer to Box #71)
  • Ensuring Element Stays Centered, Particularly During Screen Resizing

Answer №2

Perhaps a different strategy could be beneficial. Here is an alternative suggestion.

.wrapper {
  display: flex;
  justify-content: space-between;
  background-color: lightblue;
}

.wrapper > div {
   flex-basis: 30%; 
   text-align: center;
}
<div class="wrapper">
 <div>small</div>
 <div>medium element here</div>
 <div>longer element is here too</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

Using jQuery to emphasize search text in a user-friendly manner

After successfully implementing a search function for a table, I faced the challenge of highlighting the search keyword within a cell. Despite searching for a solution online, I couldn't find anything useful! Here is my HTML code: <table class="s ...

What is the best way to showcase a full-screen overlay directly inside an iFrame?

As I work in HTML, I'm faced with a challenge - my iFrame is only taking up a small section of the screen (referred to as 'World' in the example below). What I want to achieve is creating a full-screen div overlay from that iFrame, but curr ...

How to Maintain SASS Code Efficiency with Media Queries

How can I avoid repeating myself in my CSS code when using two different media queries for phones and tablets that require the same exact styling? $mobile-portrait: "only screen and (max-width: 680px)"; $tablet-portrait: "only screen and (min-device-wid ...

Having trouble getting my <a> tags to function properly on my GitHub webpage, even though they work perfectly fine on Codepen

I recently completed a random quote generator webpage project as part of my freecodecamp curriculum. I decided to upload the files to GitHub in order to host them as standalone webpages. While the page works perfectly on CodePen, I encountered an issue wit ...

Error: Attempting to append a child to a non-existent property

I am currently learning Java Script and this is the code I have been working on. <!doctype html> <html> <head> <style> div {position:absolute; width:500px; height:500px} img {position:absolute} ...

Incorporating additional information into the database

When I run the code, I see a table and a button. After entering data in the prompts as instructed, the table does not get updated. I'm unsure why this is happening. Can someone please explain? <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Trans ...

Retrieve the href attribute from a hyperlink positioned above a different element using Selenium

My challenge in using selenium is to extract an href from a link buried within numerous tags! The only identifiable detail I can work with is the presence of the text "Test text!" in the h3 tag as shown in the example below: <a href="/li ...

Enhance your textbox with more detailed descriptions than just displaying NaN

I am working on a form that includes select boxes. If a user selects an option from "Convert From" and another option from "Convert To" but does not enter a number in the input field, instead of displaying NaN in the result text box, I would like to show ...

Repeat the execution or refresh an EventListener

I am a beginner in the world of coding, currently working on my inaugural project to create a web-based game using HTML, CSS, and JavaScript. I have encountered an issue with the .addEventListener() method that I couldn't seem to find a solution for ( ...

What steps should I take to ensure that the login page functions properly?

Below is the HTML code: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Login Pag ...

The hover functionality fails to activate when a z-index is applied

My issue revolves around 2 divs: one containing a link and the other a box-shaped container. The link is set with position:fixed; causing it to fly over the container div. To resolve this, I attempted to assign a negative z-index value to the link, but unf ...

Conceal any zero values from an empty numerical input

Currently, I have a form that retrieves data from a database and includes a number input type field. When the field is empty, it defaults to displaying "0." However, I would like to hide the "0" and only show the value if it is different from 0. Despite a ...

4 products - all discounted by 25% - featuring stylish borders and margins

After extensively searching the internet, I have come across similar issues but not quite the same as mine. I have a list that I want to display in table form within a parent div taking up the entire width (100%). I aim to show 4 items per row and attempt ...

jQuery is an excellent tool for implementing drag and drop folder upload functionality, all without

I am creating a drag and drop file uploader with basic functionality. Here is the code: HTML: <div class="drop-box drop-area"> <form enctype="multipart/form-data" id="yourregularuploadformId"> <input type="file" name="files[]" ...

Ways to trigger a modal programmatically in the backend code?

My goal is to trigger the display of a modal when a button is clicked. The modal should be shown by clicking this button: <asp:Button ID="Button4" runat="server" class="btn btn-info" data-toggle="modal" OnClientClick="return false;" data-target="#View1 ...

Easily validate the contenteditable attribute of <td> element

I am currently working on a table that displays data from a MYSQL database. Whenever a user makes changes to an element in the table, I want the database to be updated using AJAX. Below is my JavaScript code for sending data in an editable row. function s ...

Why is my bootstrap-enhanced website appearing unattractive on MSIE 8?

Check out my website at My website displays perfectly in browsers like Firefox, Chrome, Opera, and the Android Browser. However, when I viewed it on Internet Explorer 8 at my parent's house, it looked all messed up. How can I improve the compatibilit ...

Can JSF Ajax be used to update non-JSF components like plain HTML elements?

Is it feasible to make changes to sections of my webpage that are not JSF elements? For instance, can I modify a simple HTML <div> or should I enclose it in a JSF component? ...

The element's height appears to be fluctuating unexpectedly when I attempt to adjust it using percentage values within a narrow range

I'm utilizing React and Bootstrap in this project. Here's an overview of my code: I have an element with height set to 0, in rem. My goal is to make the height of this element increase as I scroll down the page, creating the illusion that it is ...

What is the best way to create a centered vertical line with text in the middle?

I attempted to replicate a form that contains a vertical line <span class="vertical-line">or</span> with text centered in it! How can I create a similar appearance like this form? I considered using hr but it generates a horizontal ...