Home > Software engineering >  Use flexbox to space elements evenly
Use flexbox to space elements evenly

Time:01-13

I am currently working on a project where I have to create four quarters for a year using flexbox. I would like all the quarters to be spaced evenly with the year above quarter 2 and quarter 3. I know I have to use justify-content: space-evenly, but the problem is that quarter 2 and quarter 3 are too close to each other because they are in a container along with the year. I will leave the HTML and CSS here in case you want to see it in js fiddle.

HTML

<div >
  <div>Q1</div>
    <div>
      <div >2022</div>
        <div >
          <div>Q2</div>
          <div>Q3</div>
        </div>
    </div>
  <div>Q4</div>
</div>

CSS

.container {
  display: flex;
  align-items: flex-end;
  justify-content: space-evenly;
}

.yearContainer {
  display: flex;
  justify-content: center;
}

.q2q3Container {
  display: flex;
}

My problem is that I don't know how to space out q2 and q3 so they have the same space as q1 and q4. I will leave pictures on how I image it to look like, also a real application of the view. enter image description here. enter image description here

enter image description here

Thanks for any help.

CodePudding user response:

I would use grid for that design. But if you want to use flex, you can use flex-basis to define
an area of 25% | 50% | 25% space. Then you can use justify-content: space-around; in the Q2, Q3 to evenly space the content. I also used text-align: center in main container.

.container {
  display: flex;
  align-items: flex-end;
  text-align: center;
}

.yearContainer {
  flex-basis: 50%;
  display: flex;
  justify-content: center;
}

.q2q3Container {
  display: flex;
  justify-content: space-around;
}

.fb-25 {
  flex-basis: 25%;
}

.fb-50 {
  flex-basis: 50%;
}
<div >
  <div >Q1</div>
  <div >
    <div >2022</div>
    <div >
      <div>Q2</div>
      <div>Q3</div>
    </div>
  </div>
  <div >Q4</div>
</div>

  •  Tags:  
  • Related