craig-nerd
craig-nerd

Reputation: 748

How to align child components horizontally to occupy a certain percentage of the container's width?

I have three different React components in the following format:

<Container className={"parent"}>
    <h2>Heading</h2>
    <Tabs className={"childOne"}/>
    <Info className={"childTwo"}/>
</Container> 

Each of the above child components render other child components and native html tags like <div>s and <span>s.

This is how I want the components to render on the browser:

Component layout

I have tried achieving this using CSS flex-box. However, the child components only take up the width of their content and I am not able to proportion their widths into 66% and 33% of the container respectively (with some gap in between). This is the CSS I tried:

.parent {
  display: flex;
  flex-direction: row;
}

.childOne {
  flex-basis: 70%;
}

.childTwo {
  flex-basis: 30%;
}

I also tried display: inline-block; and float:left on each of the child components but this did not even align the children horizontally.

Could someone please show me how I can achieve this? Thanks!

Upvotes: 2

Views: 1207

Answers (2)

Jakub Muda
Jakub Muda

Reputation: 6714

The easiest way to do it is to use flexbox. Here you have an example. You can add as many columns as you want.

Code based on Bootstrap 5.

.row{
  display:flex;
  flex:1 0 100%;
  flex-wrap:wrap;
}
.row > *{
  flex-shrink:0;
  width:100%;
  max-width:100%;
}
.col-4{
  flex:0 0 auto;
  width:33.333333%;
}
.col-8{
  flex:0 0 auto;
  width:66.666667%;
}
/*DEMO*/*{box-sizing:border-box}.col-4,.col-8{padding:1.5rem;border:1px solid red}
<div class="row">
  <div class="col-8">A</div>
  <div class="col-4">B</div>
</div>

Upvotes: 1

Mohamed Ali
Mohamed Ali

Reputation: 141

You're using flex-basis: 50% on both which will be equal and not as you expected it. Maybe make childOne flex-basis of 70%?

You can also make flex: 2 on childOne and flex: 1 on child two.

Here is a code example: https://codepen.io/jsmohamed/pen/XWXaMbp

Upvotes: 0

Related Questions