How to make a div fill the remaining width with pure Css

Asked

Viewed 90 times

0

I have the following html code:

<div class='pai'>
      <div class='filho1'>  Texto Qualquer que eu não sei o tamanho de caracteres </div>
      <div class='filho2'>  Componente que deve preencher a largura restante </div>
</div>

I need '.Filho1' to have its size according to its content and that . Fil2 fill in the remaining space until it reaches the '.pai' width limit.'

I know div . Fil1 and . Fil2 inherit the properties of the parent so I left css as follows

.pai{
    margin: 0;
    padding: 0;
    width: 100%;
}
.filho1{
    width: auto;
    background-color: red;
}
.filho2{
    width: 100%;
    background-color: red;
}

however I want child 2 to be the size of ( (100% of .parent) - (width of .child 1) ) and I’m having a hard time.

1 answer

2


Hello! apply the "display:flex" property to the parent div, which will allow the easing of the arrangement of your child elements and to the div that will take over the rest of the container space the "flex-Grow: 1" property, which will cause it to "grow" until it occupies the remaining total space. I changed the color of the Filho2 class to facilitate the visualization. Maybe in the snippet there is not enough space to view, put to open the whole screen. But you can copy the css and test that it is correct.

.pai {
  margin: 0;
  padding: 0;
  width: 100%;
  display: flex;
}

.filho1 {
  background-color: red;
}

.filho2 {
  background-color: blue;
  flex-grow: 1;
}
<div class='pai'>
  <div class='filho1'> Texto Qualquer que eu não sei o tamanho de caracteres </div>
  <div class='filho2'> Componente que deve preencher a largura restante </div>
</div>

  • 1

    I didn’t know about the flex property, but that’s exactly what I needed, thank you very much .

  • a div can be a flex container and at the same time a flex item ?

  • 1

    You can. Do a read on this link: https://origamid.com/projects/flexbox-fullguide/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.