Home > Net >  Div vanishes when i use "align-items : center"
Div vanishes when i use "align-items : center"

Time:11-19

I want to create a box which has on left and right side a blue "div" and in the middle a larger purple "div". My Problem is that when i write "align-items : center" all "div" vanishes but i dont know why. Can you help me?

This is my HTML Code

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Flexbox Playground</title>
    <link href="https://fonts.googleapis.com/css2?family=Open Sans:wght@300&display=swap" rel="stylesheet">

    <link rel="stylesheet" href="app.css">
</head>

<body>
    <h1>Let's Play With Flexbox</h1>

    <section id="anotherExample">
        <div ></div>
        <div ></div>
        <div ></div>
    </section>

</body>

</html>

This is my CSS Code

#anotherExample{
    width: 90%;
    height: 500px;
    margin: 0 auto;
    border: 5px solid #003049;
    display: flex;
    justify-content: center;
    /*align-items: center;*/
 }
 
 section .sidebar{
    background-color: blue;
    flex-grow:1 ;
    flex-basis: 200px;

 }

 section .mainContent{
    background-color: blueviolet;
    flex-grow:2 ;
    flex-basis: 200px;
 }

CodePudding user response:

It looks like when you apply align-items: center, the height of div elements are set to 0. You can try to add the height property to divs to see them again as #anotherExample is parent of those div elements.

#anotherExample{
    width: 90%;
    height: 500px;
    margin: 0 auto;
    border: 5px solid #003049;
    display: flex;
    justify-content: center;
    align-items: center;
 }
 
 section .sidebar{
    height: 100%;
    background-color: blue;
    flex-grow:1;
    flex-basis: 200px;

 }

 section .mainContent{
    height: 100%;
    background-color: blueviolet;
    flex-grow:2 ;
    flex-basis: 200px;
 }
<h1>Let's Play With Flexbox</h1>

    <section id="anotherExample">
        <div ></div>
        <div ></div>
        <div ></div>
    </section>

CodePudding user response:

All div vanish because they have no height when align-items: center.

For flex items, the default align-items behave as stretch. The three div are stretched to their container height.

When you set align-items: center, the three div are centered on the cross-axis, but they are not visible due to no height (since they do not have content or a set height).

If you give them a height such as height: 100%, you can see the three div again.

More about align-items

Example:

#anotherExample {
  width: 90%;
  height: 500px;
  margin: 0 auto;
  border: 5px solid #003049;
  display: flex;
  justify-content: center;
  /*            
  • Related