[css] Can we define min-margin and max-margin, max-padding and min-padding in css?

Can we define min-margin and max-margin, max-padding and min-padding in CSS ?

This question is related to css margin padding

The answer is


UPDATE 2020

With the new (yet in Editor's draft) CSS 4 properties you can achieve this by using min() and max() (also you can use clamp() as a - kind of - shorthand for both min() and max()

clamp(MIN, VAL, MAX) is resolved as max(MIN, min(VAL, MAX))

min() syntax:

min( <calc-sum># )

where 
<calc-sum> = <calc-product> [ [ '+' | '-' ] <calc-product> ]*

where 
<calc-product> = <calc-value> [ '*' <calc-value> | '/' <number> ]*

where 
<calc-value> = <number> | <dimension> | <percentage> | ( <calc-sum> )

max() syntax:

max( <calc-sum># )
    
where
<calc-sum> = <calc-product> [ [ '+' | '-' ] <calc-product> ]*
    
where  
<calc-product> = <calc-value> [ '*' <calc-value> | '/' <number> ]*

where 
<calc-value> = <number> | <dimension> | <percentage> | ( <calc-sum> )

clamp() syntax:

clamp( <calc-sum>#{3} )

where 
<calc-sum> = <calc-product> [ [ '+' | '-' ] <calc-product> ]*

where 
<calc-product> = <calc-value> [ '*' <calc-value> | '/' <number> ]*

where 
<calc-value> = <number> | <dimension> | <percentage> | ( <calc-sum> )

Snippet

_x000D_
_x000D_
.min {
  /* demo */
  border: green dashed 5px;
  /*this your min padding-left*/
  padding-left: min(50vw, 50px);
}

.max {
  /* demo */
  border: blue solid 5px;
  /*this your max padding-left*/
  padding-left: max(50vw, 500px);
}

.clamp {
  /* demo */
  border: red dotted 5px;
  /*this your clamp padding-left*/
  padding-left: clamp(50vw, 70vw, 1000px);
}


/* demo */

* {
  box-sizing: border-box
}

section {
  width: 50vw;
}

div {
  height: 100px
}


/* end of demo */
_x000D_
<section>
  <div class="min"></div>
  <div class="max"></div>
  <div class="clamp"></div>
</section>
_x000D_
_x000D_
_x000D_


Old Answer

No you can't.

margin and padding properties don't have the min/max prefixes

An approximately way would be using relative units (vh/vw), but still not min/max

And as @vigilante_stark pointed out in the answer, the CSS calc() function could be another workaround, something like these:

_x000D_
_x000D_
/* demo */

* {
  box-sizing: border-box
}

section {
  background-color: red;
  width: 50vw;
  height: 50px;
  position: relative;
}

div {
  width: inherit;
  height: inherit;
  position: absolute;
  top: 0;
  left: 0
}


/* end of demo */

.min {
  /* demo */
  border: green dashed 4px;
  /*this your min padding-left*/
  padding-left: calc(50vw + 50px);
}

.max {
  /* demo */
  border: blue solid 3px;
  /*this your max padding-left*/
  padding-left: calc(50vw + 200px);
}
_x000D_
<section>
  <div class="min"></div>
  <div class="max"></div>
</section>
_x000D_
_x000D_
_x000D_


You can also use @media queries to establish your max/min padding/margin (but only according to screen size):

Let's say you want a max padding of 8px, you can do the following

div {
  padding: 1vh 0;
}
@media (max-height: 800px) {
  div {
    padding: 8px 0;
  }
}

I was looking for a solution to make the contents of a row behave like in a fixed width container, but with shrinking browser width make a minimal margin from the left (in my case: so that the row contents do not hide under a big logo with position: absolute in left-top).

This is what worked for me:

HTML

<div class="parent-container">
  <div class="child-container">
    <h1>Some header</h1>
  </div>
</div>

CSS

.parent-container {
  padding-left: min(150px);
}
.child-container {
  padding-left: calc( 50vw - 500px );
}

When I scale the browser window left and right, my h1 doesn't go to the left more than the 150px, but goes right following the behavior of my next row's content set to display in a fixed container.


margin and padding don't have min or max prefixes. Sometimes you can try to specify margin and padding in terms of percentage to make it variable with respect to screen size.

Further you can also use min-width, max-width, min-height and max-height for doing the similar things.

Hope it helps.


See this CodePen https://codepen.io/ella301/pen/vYLNmVg which I created. I used 3 CSS functions min, max and calc to make sure the left and right paddings are fluid between minimum 20px and maximum 120px.

 padding: 20px max(min(120px, calc((100% - 1198px) / 2)), 20px);

Hope it helps!


Comming late to the party, as said above there unfortunately is no such thing as max-margin. A sollution that helped me is to place a div above the item you want to have the max-margin applied to.

<body style="width:90vw; height:90vh;">
    <div name="parrentdiv/body" style="width:300px; height:100%; background-color: blue">
        <div name="margin top" style="width:300px; height:50%; min-height:200px; background-color: red"></div>
        <div name="item" style="width:300px; height:180px; background-color: lightgrey">Hello World!</div>
    </div>
</body>

Run above coded snippet in full page and resize the window to see this working. The lightgreypart will have the margin-top of 50% and a 'min-margin-top' of 200px. This margin is the red div (wich you can hide with display: none; if you want to). The blue part is what's left of the body.

I hope this will help people with the same problem in the future.


I wrote a library to do this, you can view it here: https://codepen.io/nicetransition/pen/OyRwKq

to use in your case:

.selector {
    scale($context, $base-size, $limit-size-min, $limit-size-max, $property: padding-right);
    scale($context, $base-size, $limit-size-min, $limit-size-max, $property: padding-left);
}
  • $context: Max-width of your container

  • $base-size: Root font size

  • $limit-size-min: The minimum size

  • $limit-size-max: The maximum size

    .selector { scale(1400px, 16px, 5px, 20px, $property: padding-right); scale(1400px, 16px, 5px, 20px, $property: padding-left); }

This would scale down to 5px and up to 20px, between 5-20 it is dynamic based of vw


var w = window.innerWidth;
var h = window.innerHeight;
if(w < 1116)
    document.getElementById("profile").style.margin = "25px 0px 0px 975px";
else
    document.getElementById("profile").style.margin = "25px 0px 0px 89%";

Use code above as an example of how to set min-margin and padding


@vigilante_stark's answer worked for me. It can be used to set a minimum "approximately" fixed margin in pixels. But in a responsive layout, when the width of the page is increasing margin can be increased by a percentage according to the given percentage as well. I used it as follows

example-class{
  margin: 0 calc(20px + 5%) 0 0;
}

I ran across this looking for a way to do a max-margin for responsive design. I need a 5% margin for mobile/tablet devices up to 48 pixels wide. Berd gave me the answer by using media queries.

My answer: 48 * 2 = 96 total max margin 96 is 10% of total width. 10 * 96 = (960) 100% of vw where 48px is the first time I want it to overwrite the % .

So my media queries to control my margins become:

@media (max-width: 959px) {
    .content {
        margin: 30px 5% 48px;
    }
}
@media (min-width: 960px) {
    .content {
        display:block;
        margin: 30px 48px 48px;
    }
}

I use this hack of defining the minimum margin required then the auto example:

margin-left: 20px+auto;

margin-right: 20px+auto;

this makes a minimum cushion area and automatically align the view


I think I just ran into a similar issue where I was trying to center a login box (like the gmail login box). When resizing the window, the center box would overflow out of the browser window (top) as soon as the browser window became smaller than the box. Because of this, in a small window, even when scrolling up, the top content was lost.

I was able to fix this by replacing the centering method I used by the "margin: auto" way of centering the box in its container. This prevents the box from overflowing in my case, keeping all content available. (minimum margin seems to be 0).

Good Luck !

edit: margin: auto only works to vertically center something if the parent element has its display property set to "flex".


This seems to work for me to make a responsive iframe embed with a max height set.

.embed-container {
    position: relative;
    padding-bottom: min(80vh, 100%);
    width: 100%;
    height: 100%;
    max-height: 80vh;
    overflow: hidden;
    max-width: 100%;
  }
  .embed-container iframe,
  .embed-container object,
  .embed-container embed {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    max-height: 80vh;
  }

<div class="embed-container">
  <iframe
    src="https://player.vimeo.com/video/405184815?title=0&byline=0&portrait=0"
    frameborder="0"
    webkitAllowFullScreen
    mozallowfullscreen
    allowfullscreen
  ></iframe>


Late to the party, but I'd like to share my simple solution. I'm gonna assume that if we want something that would work like a min-margin, it's because we have a margin: auto; in the first place, and we don't want that margin auto being smaller than a certain number.

We can do that with two div, one inside another.

Here is an example with horizontal margins.

<div class="margin-auto">
  <div class="min-margin">
    <p>Lorem Ipsum etc</p>
  </div>
</div>

As for the css:

.margin-auto {
  margin: 0 auto;
}

.min-margin {
  margin: 0 16px;
  max-width: 300px;
}

Unfortunately you cannot.
I tried using the CSS max function in padding to attempt this functionality, but I got a parse error in my css. Below is what I tried:

padding: 5px max(50vw - 350px, 10vw);

I then tried to separate the operations into variables, and that didn't work either

  --padding: calc(50vw - 350px); 
  --max-padding: max(1vw, var(--padding));
  padding: 5px var(--max-padding);

What eventually worked was just nesting what I wanted padded in a div with class "centered" and using max width and width like so

 .centered {
   width: 98vw;
   max-width: 700px;
   height: 100%;
   margin: 0 auto;
}

Unfortunately, this appears to be the best way to mimic a "max-padding" and "min-padding". I imagine the technique would be similar for "min-margin" and "max-margin". Hopefully this gets added at some point!


I was faced with the same problem today. Apparently the solution is as simple as using :

padding: calc(*put fixed pixels here*px + *put your required %age here*%) 

Note that you do have to decrement the required %age a little to account for fixed pixels.


Try using the css properties min and max as a workaround

For example:

width: min(50vw, 200px);

means the width will be the smallest of the two values.

width: max(50vw, 200px);

means the width will be the larger of the two values.

More details here:

https://developer.mozilla.org/en-US/docs/Web/CSS/min


Ideally, margins in CSS containers should collapse, so you can define a parent container which sets its margins(s) to the minimum you want, and then use the margin(s) you want for the child, and the content of the child will use the larger margins between the parent and child margin:

  • if the child margin(s) are smaller than the parent margin(s)+its padding(s), then the child margins(s) will have no effect.

  • if the child margin(s) are larger than the parent margin(s)+its padding(s), then the parent padding(s) should be increased to fit.

This is still frequently not working as intended in CSS: currently CSS allows margin(s) of a child to collapse into the margin(s) of the parent (extending them if necesary), only if the parent defines NO padding and NO border and no intermediate sibling content exist in the parent between the child and the begining of the content box of the parent; however there may be floatting or positioned sibling elements, which are ignored for computing margins, unless they use "clear:" to also extend the parent's content-box and compltely fit their own content vertically in it (only the parent's height of the content-box is increased for the top-to-bottom or bottom-to-top block-direction of its content box, or only the parent's width for the left-to-right or right-to-left block-direction; the inline-direction of the parent's content-box plays no role) .

So if the parent defines only 1px of padding, or only 1px of border, then this stops the child from collapsing its margin into the parent's margin. Instead the child margins will take effect from the content box of the parent (or the border box of the intermediate sibling content if there's any one). This means that any non-null border or non-null padding in the parent is treated by the child as if this was a sibling content in the same parent.

So this simple solution should work: use an additional parent without any border or padding to set the minimum margin to nest the child element in it; you can still add borders or paddings to the child (if needed) where you'll defining its own secondary margin (collapsing into the parent(s) margins) !

Note that a child element may collapse its margin(s) into several levels of parents ! This means that you can define several minimums (e.g. for the minimum between 3 values, use two levels of parents to contain the child).

Sometimes 3 or more values are needed to account for: the viewport width, the document width, the section container width, the presence or absence of external floats stealing space in the container, and the minimum width needed for the child content itself. All these widths may be variable and may depend as well on the kind of browser used (including its accessibility settings, such as text zoom, or "Hi-DPI" adjustments of sizes in renderers depending on capabilities of the target viewing device, or sometimes because there's a user-tunable choice of layouts such as personal "skins" or other user's preferences, or the set of available fonts on the final rendering host, which means that exact font sizes are hard to predict safely, to match exact sizes in "pixels" for images or borders ; as well users have a wide variety of screen sizes or paper sizes if printing, and orientations ; scrolling is also not even available or possible to compensate, and truncation of overflowing contents is most often undesirable; as well using excessive "clears" is wasting space and makes the rendered document much less accessible).

We need to save space, without packing too much info and keeping clarity fore readers, and ease of navigation : a layout is a constant tradeoff, between saving space and showing more information at once to avoid additional scrolling or navigation to other pages, and keeping the packed info displayed easy to navigate or interact with).

But HTML is often not enough flexible for all goals, and even if it offers some advanced features, they becomes difficult to author or to maintain/change the documents (or the infos they contain), or readapt the content later for other goals or presentations. Keeping things simple avoids this issue and if we use these simple tricks that have nearly no cost and are easy to understand, we should use them (this will always save lot of precious time, including for web designers).


Examples related to css

need to add a class to an element Using Lato fonts in my css (@font-face) Please help me convert this script to a simple image slider Why there is this "clear" class before footer? How to set width of mat-table column in angular? Center content vertically on Vuetify bootstrap 4 file input doesn't show the file name Bootstrap 4: responsive sidebar menu to top navbar Stylesheet not loaded because of MIME-type Force flex item to span full row width

Examples related to margin

Can we define min-margin and max-margin, max-padding and min-padding in css? Does bootstrap have builtin padding and margin classes? Removing body margin in CSS How do I force a vertical scrollbar to appear? How to adjust gutter in Bootstrap 3 grid system? How to disable margin-collapsing? Why is there an unexplainable gap between these inline-block div elements? Remove "whitespace" between div element Remove all padding and margin table HTML and CSS Using margin / padding to space <span> from the rest of the <p>

Examples related to padding

Can we define min-margin and max-margin, max-padding and min-padding in css? Does bootstrap have builtin padding and margin classes? Adding space/padding to a UILabel How to adjust gutter in Bootstrap 3 grid system? Why is there an unexplainable gap between these inline-block div elements? How to increase the distance between table columns in HTML? Absolute positioning ignoring padding of parent Remove all padding and margin table HTML and CSS Style the first <td> column of a table differently Using margin / padding to space <span> from the rest of the <p>