Search code examples
htmlcsspaddingmargin

How i can use min and max CSS functions to work with auto


I want to be able to use the common margin: auto property, but with a minimum margin, such as:

margin: 0 max(auto, 16px);

This would center an element horizontally & still enforce 16px of margin on either side when the viewport is too small. but not worked min() and max() CSS with margin: auto;

for example: I want to set style margin-left: 30px; and margin-right: 30px; for .navbar__menu when screen lower 500px. (without use @media query)

.navbar__menu {
  max-width: 500px;
  height: 50px;
  position: absolute;
  top: 100px;
  left: 0;
  right: 0;
  margin-left: auto;
  margin-right: auto;
  background: red;
  display: flex;
}
<div class="navbar__menu">

</div>


Solution

  • Use margin-inline: max(30px,50% - 500px/2) and no need to set a max-width

    .navbar__menu {
      height: 50px;
      position: absolute;
      top: 100px;
      left: 0;
      right: 0;
      margin-inline: max(30px,50% - 500px/2);
      background: red;
      display: flex;
    }
    <div class="navbar__menu">
    
    </div>

    More detail on my blog: https://css-tip.com/center-max-width/