Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a percentage margin in CSS but want a minimum margin in pixels?

Tags:

css

margin

I have set a margin: 0 33% 0 0; however I would also like to make sure the margin is at least a certain px amount. I know there is no min-margin in CSS so I was wondering if I have any options here?

like image 604
Brett Avatar asked Jun 14 '11 22:06

Brett


People also ask

Can you set a minimum margin CSS?

Yes, you can! In 2020 this is now very straightforward using the CSS math functions: min(), max(), and clamp(). A min calculation picks the smallest from a comma separated list of values (of any length). This can be used to define a max-padding or max-margin rule: padding-right: min(50px, 5%);

Can you use percentages in margin CSS?

You can combine fixed value and percentage values in the CSS margin property. Negative values are allowed in the CSS margin property. When the value is provided as a percentage, it is relative to the width of the containing block. See also margin-top, margin-bottom, margin-left, and margin-right.

Should I use px or percent in CSS?

Clearly, there is nothing right or wrong. With pixels, it is easy to position objects relative to each other and controls specific heights and widths. On the other hand, scaling objects with percentages is easy. % Is the way to go in a modern world like vector graphics.


1 Answers

The true solution here is to use a media query break-point to determine when 33% no longer works for you and should be overridden by the minimum margin in pixels.

/*Margin by percentage:*/ div{     margin: 0 33% 0 0; }  /*Margin by pixel:*/ @media screen and ( max-width: 200px ){     div{         margin: 0 15px 0 0;     } } 

In the above code, change the max-width to whatever screen width the 33% right margin no longer works for you.

like image 62
Clarus Dignus Avatar answered Sep 21 '22 13:09

Clarus Dignus