Home > Back-end >  Is there a way to vertically-center text in this Flexbox case without nesting flexboxes?
Is there a way to vertically-center text in this Flexbox case without nesting flexboxes?

Time:05-17

I'm playing around with flex-direction:column to understand this property better. Here's the code I've (codepen is here: https://codepen.io/Chiz/pen/ZEreLrQ) :

HTML:

<div >
  <div >RED</div>
  <div >ORANGE</div>
  <div >YELLOW</div>
  <div >GREEN</div>
  <div >BLUE</div>
</div>

CSS:

.container {
  display:flex;
  flex-direction:column;
  justify-content:space-between;
  align-items:center;
  max-width: 800px;
  height: 500px;
  border: 1px solid black;
}

div div
{
  text-align:center;
  padding:30px 30px;
  width:20%;
  flex:1;
}

.red { background-color:red; }
.orange { background-color:orange; }
.yellow { background-color:yellow; }
.green { background-color:green; }
.blue { background-color:blue; }

Notice the text in the colored boxes are not vertically aligned. What causes this, and is there a way to align them vertically without nesting flexboxes within flexboxes?

CodePudding user response:

By removing text-align: center; on that div div, you get what you want (I think), like so:

.container {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  align-items: center;
  max-width: 800px;
  height: 500px;
  border: 1px solid black;
}

div div {
  padding: 30px 30px;
  width: 20%;
  flex: 1;
}

.red {
  background-color: red;
}
.orange {
  background-color: orange;
}
.yellow {
  background-color: yellow;
}
.green {
  background-color: green;
}
.blue {
  background-color: blue;
}
<div >
  <div >RED</div>
  <div >ORANGE</div>
  <div >YELLOW</div>
  <div >GREEN</div>
  <div >BLUE</div>
</div>

CodePudding user response:

Actually the reason the boxes look like that is: padding

To center text and content both horizontally and vertically in flex logic, you can add justify-content and align-items to the boxes.

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

For your question:

.container {
  display:flex;
  flex-direction:column;
  justify-content:space-between;
  align-items:center;
  max-width: 800px;
  height: 500px;
  border: 1px solid black;
}

div div
{
  width:20%;
  flex:1;
  
  display: flex;
  justify-content: center;
  align-items: center;
}

.red { background-color:red; }
.orange { background-color:orange; }
.yellow { background-color:yellow; }
.green { background-color:green; }
.blue { background-color:blue; }
<div >
  <div >RED</div>
  <div >ORANGE</div>
  <div >YELLOW</div>
  <div >GREEN</div>
  <div >BLUE</div>
</div>

  • Related