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

Viewed 1019

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>

2 Answers

Use margin-inline: max(30px,50% - 500px/2) and no need to set a max-width (more detail: https://twitter.com/ChallengesCss/status/1469270181205749771)

.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>

Sorry if I didn't bother inspecting the code too much, but for me, in a block element, it worked well enough to set just a padding-inline as the minimum "margin" in conjunction with margin-left: auto and margin-right: auto. Ok, the minimum is not really a margin, but the effect is the same if in the element you didn't have any previous padding: it wont add up to the empty space you will get on both sides when centered.

I use this in conjunction with a width: min-content and works perfectly when dealing with an inner table that can grow wider than the available screen space, allowing this minimum empty space on smaller screens and without having to worry with fixed screen resolutions neither max(), min() or other CSS calculations.

Have to aknowledge user Temani Afif because he gave me the inspiration for my solution after reading his answer.

Related