Home > OS >  Why doen't width with percentage work in CSS?
Why doen't width with percentage work in CSS?

Time:05-31

Here is my code and it works well.

.c-table {
  display: flex;
  flex-wrap: wrap;
}

.c-plate {
  width: 50px;
  height: 96px;
}

.red {
  background: red;
}

.blue {
  background: blue;
}

.yellow {
  background: yellow;
}
<div >
   <div ></div>
   <div ></div>
   <div ></div>
</div>

I changed width of .c-plate like this:

.c-plate {
  width: 50%;
  height: 96px;
}

.c-table {
  display: flex;
  flex-wrap: wrap;
}

.c-plate {
  width: 50%;
  height: 96px;
}

.red {
  background: red;
}

.blue {
  background: blue;
}

.yellow {
  background: yellow;
}
<div >
   <div ></div>
   <div ></div>
   <div ></div>
</div>

I expected that the width of each div with c-plate class becomes 50% of the c-table width.

However, it doesn't work as expected.

CodePudding user response:

It works like expected. the with of the child (c-plate) is relative to the width from the parent (c-table).

It means if you want change the relative width from the c-plate elements you must set the width on c-table.

body {
    background: black;
}

.c-table {
  display: flex;
  flex-wrap: wrap;  
  width: 50%;
  background: gray;
}

.c-plate {
  width: 50%;
  height: 96px;
}

.red {
  background: linear-gradient(to right, red 0 50%, white 50% 100%);
}

.blue {
  background: linear-gradient(to right, blue 0 50%, white 50% 100%);
}

.yellow {
  background: linear-gradient(to right, yellow 0 50%, white 50% 100%);
}
<div >
   <div ></div>
   <div ></div>
   <div ></div>
</div>

CodePudding user response:

As noted by @Geeky Quentin, it is the intended behaviour.

You set .c-plate to have 50% width. Elements with .c-plate will look for its parent to take 50% of. Since your .c-table does not have a width property set, it just becomes 50% of body.

You can set the width of .c-table to make .c-plates inherit from that width. However, it will still be 50% and since there are 3 .c-plates, it will be 150% total and wrap around to the next line since flex-wrap is wrap.

.c-table {
  display: flex;
  flex-wrap: wrap;
  
  width: 500px;
}

.c-plate {
  width: 50%;
  height: 96px;
}

.red {
  background: red;
}

.blue {
  background: blue;
}

.yellow {
  background: yellow;
}
<div >
   <div ></div>
   <div ></div>
   <div ></div>
</div>

If this is not the desired outcome, you will have to be more specific what you want.

Do you want to have something like this?

.c-table {
  display: flex;
  flex-wrap: wrap;
  
  width: 500px;
}

.c-plate {
  width: 33%;
  height: 96px;
}

.red {
  background: linear-gradient(to right, red 0 50%, white 50% 100%);
}

.blue {
  background: linear-gradient(to right, blue 0 50%, white 50% 100%);
}

.yellow {
  background: linear-gradient(to right, yellow 0 50%, white 50% 100%);
}
<div >
   <div ></div>
   <div ></div>
   <div ></div>
</div>

  • Related