0

My question is as same as title.

Why doesn't flex-container to be the width of flex items when flex-items' padding are given as percentage?

I was trying to make a navigation menu for the website, and I found weird behaviours. Here's the code to make it more comprehensible.

 #header-container {
      height: 100%;
      padding: 0 2.9%;
    
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    
    #restaurant-title {
      font-size: 3rem;
      color: #fff;
    }
    
    #restaurant-title #kor {
      color: #E33535;
    }
    
    #nav-bar {
      display: flex;
      align-items: center;
    }
    
    #nav-bar li {
      /* This will overflow! */
      /* padding-right: 0 5%; */

      /* this doesn't overflow! */
      padding-right: 24px;
    }
    
    #nav-bar li:last-child {
      padding-right: 0;
    }
    
    #nav-bar li a {
      color: #fff;
      font-size: 2rem;
    }
 <div id="header-container">
      <h1 id="restaurant-title">DG<span id="kor">KOR</span>DISH</h1>
      <ul id="nav-bar">
        <li><a href="index.html">Home</a></li>
        <li><a href="about.html">About</a></li>
        <li><a href="menu.html">Menu</a></li>
        <li><a href="contact.html">Contact</a></li>
      </ul>
    </div>

So if I give #nav-bar li the percentage as a padding property's value, it will overflow the flex-container. Hence, flex-container #nav-bar doesn't get bigger as the whole width of its item get bigger.

However, weirdly, if I give #nav-bar li which are flex items, pixels as their padding value, it doesn't overflow and flex-container #nav-bar gets bigger as their flex items sizes.

So can someone explain,

  1. What's the difference between giving flex items padding value as percentage and as pixel in this context?
  2. Why doesn't flex-container to be the width of flex items when flex-items' padding are given as percentage and why they do stretch when given the padding value as pixel?

Full code can be found here

نور
  • 1,425
  • 2
  • 22
  • 38
Sambo Kim
  • 1,383
  • 2
  • 11
  • 12
  • 2
    Does this answer your question? [Why does percentage padding break my flex item?](https://stackoverflow.com/questions/53536266/why-does-percentage-padding-break-my-flex-item) – mttetc Aug 20 '20 at 08:58
  • you may use vw instead %, the value will be static, % padding do not reset the width of the flex container, else, calculation goes on again & again and you fall into a never ending loop each times parent's width is updated .... – G-Cyrillus Aug 20 '20 at 09:18
  • 1
    @bluebird It indeed solve my problem, thanks a lot! – Sambo Kim Aug 21 '20 at 13:43

0 Answers0