skip to Main Content

I’m trying to achieve a basic design.

I have one div container and want two containers inside that div:

Container: takes the full width of the screen/parent
Div 1: width of 200, centered inside the container.
Div 2: width of 100 and next to Div 1 on the right side with a margin on the left of 10px.

Anything I tried did push Div 1 away from the center, so that Div 1 and Div 2 were centered, but I did not achieve that Div 1 stay centered and Div 2 is just on the right side of it.

I am using React Native, so I tried the following:

<View style={{flex: 1, flexDirection: 'row', justifyContent: 'center', alignItems: 'center'}}>
   <View style={{backgroundColor:'orange', width: 200, height: 100}}></View>
   <View style={{backgroundColor:'red', marginLeft: 10, width: 200, height: 100}}></View>
</View

Any help and advice is appreciated.

2

Answers


  1. Just make a 3rd div as transparent. And, give parent .container display:flex;

    .container {background:yellow; height:100vh; width:100vw;display:flex; justify-content:center;}
    .div1, .div2, .transparent {width:100px; height:100px;} 
    .div1 {background:blue;}
    .div2 {background:orange;margin-left:10px;} 
    <div class="container"> 
      <div class="transparent"></div>
      <div class="div1"></div>
      <div class="div2"></div>
    </div>
    Login or Signup to reply.
  2. Remove the second div from the flow using position: absolute

    .container {
      display: flex;
      justify-content: center;
    }
    .container > * {
      width: 100px;
      aspect-ratio: 1;
      background: blue;
    }
    
    .two {
      background: red;
      position: absolute;
      transform: translate(calc(100% + 10px)); /* 100% + margin */
    }
    <div class="container">
      <div class="one"></div>
      <div class="two"></div>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search