Align a flex item in the center horizontally, even when neighboring items are different sizes

In a section element, I have 3 divs inside, and I am trying to horizontally center 'div 2'. The issue I am facing is that the adjacent divs are not the same size, so using "justify-content:center" is not effective.

I came across a solution here (under the title "Center a flex item when adjacent items vary in size"), but unfortunately, it does not work for my case.

Below is the relevant code snippet:

HTML

<section>
  <div id="div1">DIV 1</div>
  <div id="div2">DIV 2</div>
  <div id="div3">DIV 3</div>
</section>

CSS

section{
  display:flex;   
  position:relative;      
}   
#div1{          
  width:260px; 
}
#div2{    
  position:absolute;  
  left:50%;
  transform(translateX:-50%,0);  
}
#div3{    
  margin-left:auto;
  width:50px;
}

Also, you can find a demonstration on codepen.

The main objective here is to center 'div2' and align the other divs to the left and right edges, respectively.

Any assistance on this matter would be greatly appreciated.

Answer №1

  <article>   
    <div id="container1">Container 1</div>
    <div id="container2_wrap">
      <div id="container2">Container 2</div>
    </div>
    <div id="container3">Container 3</div>
  </article>



 article{
   display: flex;
   position:relative; 
   padding:5px;
   height: 500px;
   background:yellow;
 }
 div{
   padding:5px; 
   background:coral;
 }
 #container1{         
   width:260px; 
 }
 #container2_wrap{  
   position: absolute;
   left:50%;
   height: 100%;
   align-items: center;
   display: flex;
 }
 #container2 {
   background-color: #000fff;
 }
 #container3{    
   margin-left:auto;
   width:50px;
 }

Answer №2

To create equal width divs wrapped in another parent div, you can align the children divs inside their parent using the following method:

HTML:

<section>
  <div class="wrapper" id="div1">
    <div class="innerDiv">DIV 1</div>
  </div>
  <div class="wrapper" id="div2">
    <div class="innerDiv">DIV 2</div>
  </div>
  <div class="wrapper" id="div3">
    <div class="innerDiv">DIV 3</div>
  </div>
</section>

CSS:

section{
  display:flex;
  padding:5px;
  background:yellow;
  text-align:center;
}
.wrapper{
  display:flex;
  flex-grow:1;
  flex-wrap:wrap;
}
.innerDiv{
  padding:5px; 
  background:coral;
}
#div1{
  justify-content:flex-start;
}
#div1 .innerDiv{
  flex:1;
}

#div2{
  justify-content:center;
}
#div3{
  justify-content:flex-end;
}
#div3 .innerDiv{
  width:50px;
}

Check out the Codepen demo here

Alternatively, you can opt for a more traditional approach for better browser compatibility while keeping your HTML structure the same.

section {
  padding: 5px;
  background: yellow;
  text-align: center;
  position: relative;
  float: left;
  box-sizing: border-box;
  width: 100%;
}

div {
  padding: 5px;
  display: inline-block;
  background: coral;
}

#div1 {
  width: 260px;
  float: left;
}

#div2 {
  left: 50%;
  margin-left: -0.5em;
  position: absolute;
}

#div3 {
  float: right;
  width: 50px;
}

View the Codepen demo here

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

How can I fix my HTML Image input not redirecting when clicked?

I have successfully implemented the following code: <input type="button" name="btnHello" value="Hello" onclick="Test();"/> Here is the JS function that accompanies it: function Test() { window.location.href = "Page2.aspx"; } Initially, clicking ...

Using mix-blend-mode with an SVG image within a colored <div>: tips for applying it to the background color of your HTML

I am facing an issue with a SVG file that has mix-blend-mode styles defined on certain elements. The blending is working properly for the elements inside the SVG, but not for the background color of the HTML <div>. For instance: <!doctype html> ...

Creating a single Vuetify expansion panel: A step-by-step guide

Is there a way to modify the Vuetify expansion panel so that only one panel can be open at a time? Currently, all panels can be closed which is causing issues. I would like the last opened panel to remain open. I also want to prevent closing the currently ...

Having difficulty changing the value of a Select element in AngularJS

Struggling to update the select value from AngularJs. Check out my code below: <select ng-model="family.grade" > <option ng-repeat="option in options" value='{{option.id}}'>{{option.text}}</option> </s ...

Various background positions

Is it possible to declare multiple background positions for the same background image? I have a span with the class page_heading and I want this class to display the same image twice, once at the beginning of the text and once at the end. HTML: <h1&g ...

What is the best way to make sure the embedded object fills the entire height of the container div?

I am currently using angular2/4 along with angular-material (https://material.angular.io/). My challenge lies in trying to embed a PDF within it. The issue I am facing is that the height of the PDF object seems to be small and doesn't fully occupy the ...

AngularJS: Default value causes dropdown menu text to not display

I am facing an issue with my select menu. <select id="dd" ng-show='data != null' ng-model='search'></select> Initially, I set the filter to display only USA by default. $scope.search = 'United States of America' ...

Mobile Image Gallery by Adobe Edge

My current project involves using Adobe Edge Animate for the majority of my website, but I am looking to create a mobile version as well. In order to achieve this, I need to transition from onClick events to onTouch events. However, I am struggling to find ...

Tips for creating a clickable popover within a window that remains open but can be closed with an outside click

Is there a way to ensure that my popover window remains clickable inside its own area without closing, but automatically closes when clicked outside of the window? This is the code I am currently using, which is triggered by a button click: if (response. ...

Using the DRY principle in JavaScript to handle dynamic fields

Recently delving into Javascript, I encountered a dynamic field script that allows for adding and subtracting fields with the click of a button. The functionality is effective and serves its purpose well. $(document).ready(function() { var max_fields ...

Footer refuses to stay anchored at the bottom of the page

I'm struggling to keep my footer at the bottom of all pages on my blog. I am facing two main issues. If I use position:absolute, the footer ends up in the middle of the main blog page. Alternatively, when I don't use it, the footer sticks to the ...

Displaying feedback messages and redirecting in Flask may result in the response being visible in the developer tools, but

Just starting out with Flask and encountering an issue. I am trying to determine if a response is empty, and if it is, display a message. The problem lies in the fact that even though the redirect works and the subsequent GET request returns the correct HT ...

The custom bullet points are not appearing correctly

I've been attempting to design a custom bullet list, but it doesn't look quite right as I had hoped. The issue is that the spacing appears too close, you can see an example HERE Any suggestions would be greatly appreciated. Thank you ...

What are some techniques for disguising text on a website to give the illusion of being in English but is actually impossible to read

I am seeking a way to obscure text by rendering it completely unintelligible. While this task is easily accomplished in handwriting, I require a method for achieving this on a webpage using the Verdana font. One idea I had was to create a Verdana-style f ...

Carousel with Bootstrap: Heading positioned over the content

My goal is to have the caption of Bootstrap Carousel displayed above the content, but I'm encountering issues with it. When clicking on the chevrons, you may notice the < Item 1 > bouncing... (This behavior is a bug, and logically speaking, I ex ...

Close the ionicPopup by tapping anywhere

Currently, I have implemented an ionicPopup that automatically closes after a certain time limit. However, I am wondering if there is a way to configure it to close with a single or double tap anywhere on the screen instead. While I am aware that setting a ...

Can the hexadecimal value from an input type color be extracted and used to populate form fields that will then be displayed in a table after submission?

Hello everyone, I'm new to this platform and seeking guidance on how to improve my post! I recently created a CRUD app using Angular. It consists of a basic form with 4 fields, a color picker using input type='color', and a submit button. U ...

Adjusting the width of innerHtml within a React router link to match the parent element's width

My current challenge involves a table where a cell is represented as a link. Within this setup, I am incorporating html content into the text of the link: <TableCell align="left" classes={{root: classes.cellPadding}}> <Link className={classes.l ...

Transferring data from an Excel spreadsheet into a structured table

I am interested in transferring specific columns of data from an excel sheet to an HTML table. My goal is to populate the table based on certain conditions rather than statically inputting fixed cells. For instance, if my excel sheet has columns for Name ...

Switch up the display of table rows with a convenient Toggle Button located right after the

Looking for a way to toggle the visibility of certain rows in an HTML table using a button but having trouble placing the button after the table instead of before. Any suggestions on how to customize this setup? Thanks! /*Use CSS to hide the rows of t ...