How to use flex to get this special distribution?

My goal is to place 5 boxes on the corner and in the center.

like this

These are my codes:

.container {
      width: 240px;
      height: 200px;
      border: 1px solid gray;
      display: flex;
      flex-direction: row;
      flex-wrap: wrap;
      justify-content: space-between;
      align-content: space-between;
    }

    .container > div {
      width: 80px;
      height: 50px;
      border: 1px solid red;
      display: flex;
      justify-content: center;
      align-items: center;
    }
<body>
  <div class="container">
    <div id="one">  1</div>
    <div id="two">  2</div>
    <div id="three">3</div>
    <div id="four"> 4</div>
    <div id="five"> 5</div>
  </div>
</body>

How can I change the code so that the fifth block is in the center and the others are orderly on the corner?

>Solution :

    .container {
    width: 240px;
    height: 200px;
    border: 1px solid gray;
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    justify-content: space-between;
    align-content: space-between;
    position: relative;
}

.container > div {
    width: 80px;
    height: 50px;
    border: 1px solid red;
    display: flex;
    justify-content: center;
    align-items: center;
}

#five {
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
}
<body>
  <div class="container">
    <div id="one">  1</div>
    <div id="two">  2</div>
    <div id="three">3</div>
    <div id="four"> 4</div>
    <div id="five"> 5</div>
  </div>
</body>
  • Add position: relative; to the container so that div#5 is placed relative to it.

left: 50%; top: 50%; transform: translate(-50%, -50%); is a classic method to center a div.

Leave a Reply