1

.container {
  display: flex;
}
.container>div {
  border:2px solid red;
  padding:15px;
}
<div class="container">
  <div class="one">one</div>
  <div class="two">two</div>
</div>

I want to align the <div class="two">two</div> in the middle of the page. The first div should still on the left side. How to align the block two in the center?

  • Sorry I know thsi is not an answer, but I'm just wondering. You can use bootstrap for this. Do you just not want to use bootstrap in this case or did you not know bootstrap can do this? Not trying to attack or anything. Just wondering. – Loko Nov 15 '19 at 07:37
  • Bootstrap uses flexbox too :) (bootstrap 4) – Sfili_81 Nov 15 '19 at 07:39
  • Maybe this can help you [https://stackoverflow.com/questions/38948102/center-and-right-align-flexbox-elements](https://stackoverflow.com/questions/38948102/center-and-right-align-flexbox-elements) – Sfili_81 Nov 15 '19 at 07:39

4 Answers4

2

Can achieve this with the mix of position absolute and flex

.container {
  display: flex;
  justify-content: center; 
  position: relative;
}
.container>div {
  border:2px solid red;
  padding:15px;
}
.one-absolute {
  position: absolute;
  left: 0;
}
<div class="container">
  <div class="one one-absolute">one</div>
  <div class="two">two</div>
</div>
A. Meshu
  • 4,053
  • 2
  • 20
  • 34
Gangadhar Gandi
  • 2,162
  • 12
  • 19
0

You can use css grid to do that

 .container{
    display: grid;
    grid-template-columns: auto auto auto;
 }
.container>div {
  border:2px solid red;
  padding:15px;
  width:50px;
}
    <div class="container">
      <div class="item">one</div>
      <div class="item">two</div>
    </div>
0

Thanks for the good question, we can use two flex properties along with container class. justify-content:center; and align-items:center;

.container {
  display: flex;
  justify-content:center;
  align-items:center;
  background:pink;
  min-height:200px;
}
.container>div {
  border:2px solid red;
  padding:15px;
}
<div class="container">
  <div class="one">one</div>
  <div class="two">two</div>
</div>

Note: I additionally add min-height:400px; and background:pink; for demonstration. You can remove both of those.

0

Flex may not be the right solution for this scenario.

Instead CSS positioning could be used to align one div at the center.

But if you still want flex, add a third empty div and hide it.

<div class="container">
  <div class="one">one</div>
  <div class="two">two</div>
  <div class="three">three</div>
</div>

.

 .container {
   display: flex;
 }
 .container>div {
   border:2px solid red;
   padding:15px;
   flex: 1;
 }
 .container>div.three {
   opacity: 0;
 }