Hard Spocker Hard Spocker - 2 months ago 9
CSS Question

How to build a responsive padding for list menus using CSS?

I created a menu which looks like this centered withing a div container:

| |
| +--------+--------+--------+--------+ |
| | home | teams | games | about | |
| +--------+--------+--------+--------+ |


SC:

.main-navigation ul > li.menu-item > a {
-webkit-transition: 0.10s;
-moz-transition: 0.10s;
transition: 0.10s;

color: #fff;
background-color: #757575;
padding-top: 5px;
padding-bottom: 5px;
/* padding-left: ; i want this to be responsive
padding-right: ; */
}


What i really wanted to create though is a responsive menu which fills the white bezels on each sides.

| |
|+------------+------------+------------+----------+|
|| home | teams | games | about ||
|+------------+------------+------------+----------+|


and changes the padding size when browser resizes:

| |
|+----------+----------+----------+--------+|
|| home | teams | games | about ||
|+----------+----------+----------+--------+|


I tried adjusting the padding based on media sizes but i end up having a static look, as its only adjusting on several screen sizes and not dynamically.

Answer

This is a perfect scenario where you can use a flexbox:

  1. First reset the list styles:

    .main-navigation ul{
      list-style: none;
      padding: 0;
      margin: 0;
    }
    
  2. Now declare it as a flexbox and align them with space-around like this:

    .main-navigation ul{
      display: flex;
      justify-content: space-around;
      list-style: none;
      padding: 0;
      margin: 0;
    }
    
  3. Now add flex: 1 to each li to let it occupy all the available whitespace, and text-align: center to center the anchor tag inside the li:

    .main-navigation > ul > li {
      flex: 1;
     }
    
  4. To finish things up, added some borders and styles for illustration.

.main-navigation ul{
  display: flex;
  justify-content: space-around;
  list-style: none;
  padding: 0;
  margin: 0;
}

.main-navigation > ul > li {
  flex: 1;
  background-color: #757575;
 
  padding-top: 5px;
  padding-bottom: 5px;
  text-align: center;
  border: 1px solid #fff;
}

.main-navigation ul > li.menu-item > a {
  -webkit-transition: 0.10s;
  -moz-transition: 0.10s;
  transition: 0.10s;
  color: #fff;
}
<div class="main-navigation">
  <ul>
    <li class="menu-item"><a>home</a>
    </li>
    <li class="menu-item"><a>teams</a>
    </li>
    <li class="menu-item"><a>games</a>
    </li>
    <li class="menu-item"><a>about</a>
    </li>
  </ul>
</div>

I guess you can take it forward from here. Let me know your feedback on this. Thanks!