0

Assuming that the parent has width 100%, it is wanted to make child 1 with width 25%, child 2 with width 75%.

Those two children are some custom components that cannot have their own class so the changes must be done in the parent class.

What I've tried:

.parent {
  display: flex;
}

.parent:first-child {
  width: 25%;
  background: #ddd;
}
<div class="parent">
  <div>child 1</div>
  <div>child 2</div>
</div>

This one makes both of them having 25% of the parent in total.

Any ideas?

isherwood
  • 58,414
  • 16
  • 114
  • 157
Leo Messi
  • 5,157
  • 14
  • 63
  • 125

4 Answers4

1

Seems simple enough:

.parent {
  display: flex;
  gap: 15px;
  margin: 15px;
}

.parent > div:first-child {
  flex-basis: 25%;
  outline: 1px dotted red;
  background: #ddd;
}
.parent > div:nth-child(2) {
  flex-basis: 75%;
  outline: 1px dotted green;
}
<div class="parent">
  <div>child 1</div>
  <div>child 2</div>
</div>

By setting the flex-basis property on both child elements, you can make them take up the full width of the container.

The other option would be to set the flex-basis of the first child, and tell the second child to grow to fill the remaining space.

.parent {
  display: flex;
  gap: 15px;
  margin: 15px;
}

.parent > div:first-child {
  flex-basis: 25%;
  outline: 1px dotted red;
  background: #ddd;
}
.parent > div:nth-child(2) {
  flex-grow: 1;
  outline: 1px dotted green;
}
<div class="parent">
  <div>child 1</div>
  <div>child 2</div>
</div>

CSS Flexible Box Layout - CSS: Cascading Style Sheets | MDN
A Complete Guide to Flexbox - CSS-Tricks

Richard Deeming
  • 29,830
  • 10
  • 79
  • 151
1

Try to use css grid

.parent {
  display: grid;
  grid-template-columns: 25% 75%;
}

.parent > div {
  border: 1px solid blue;
}
<div class="parent">
  <div>child 1</div>
  <div>child 2</div>
</div>
kapantzak
  • 11,610
  • 4
  • 39
  • 61
1

Your pseudo-selector is faulty. It's looking for an element with class parent which is a first child. You want .parent :first-child, which is a descendant selector.

.parent {
  display: flex;
  justify-content: stretch;
}

.parent :first-child {
  width: 25%;
  background: #ddd;
}

.parent :last-child {
  flex: auto;
  background: pink;
}
<div class="parent">
  <div>child 1</div>
  <div>child 2</div>
</div>
isherwood
  • 58,414
  • 16
  • 114
  • 157
0

You need to update the selectors to target the child elements properly, something like :

.parent {
  width: 500px;
  height: 200px;
  display: flex;
  border: 1px solid black;
}

.parent div:first-child {
  background-color: red;
  width: 25%;
  height: 200px;
}

.parent div:nth-child(2) {
  background-color: yellow;
  width: 75%;
  height: 200px;
}
<div class="parent"> 
  <div> child1 </div>
  <div> child2 </div>
 </div>
Kanishk Anand
  • 1,686
  • 1
  • 7
  • 16