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

Viewed 88395

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?

11 Answers

you can try this

.mm:before {
    content: "";
    display: inline-block;
    width: 33%;
    min-width: 200px;
}

I know it's late in the game, but have you tried this?

margin: 0 max(33%, 20px) 0 0

where 20px is whatever you want to be at least a certain number of pixels. So the margin will stay fluid but will never fall under 20px.

Hope it helps!

I've played with a couple of the aforementioned solutions, but in a fluid and truly responsive setting, I believe the best option is to set the proper padding on the respective container/wrapper. Example: Style:

 html {
   background-color: #fff;
   padding: 0 4em;
 }
 body {
   margin: 0 auto;
   max-width: 42em;
   background-color: #ddf;
 }

Now play around with various window widths, and also try various font sizes.

Also try the working demo.

You could keep your items in a "container" div and set a padding exact to "min-margin" you'd like to have. It might not be exactly what you're looking for, but it gives you that sense of minimum margin size.

<div class="container">
   <div class="your_div_with_items">
   'items'
   </div>
</div>

Then the CSS:

.container
{
   padding: 0 'min_margin_ammount' 0 0;
}

.your_div_with_items
{
   margin: 0 33% 0 0;
}

As far as I understand, you can place a div around your element, that defines a padding. A padding of an outer element is like the margin of an inner element.

Imagine you want at least a margin of 1px:

<div style="padding:1px">
  <div style="margin: 0 33% 0 0;">
      interesting content
  </div>
</div>

edit: this is like Imigas's answer, but I think easier to understand.

It is also possible to test if a certain percentage of the screen width/height is smaller than a length in pixels.

Here is a simple solution for this using JavaScript:

<body>
 <div id="demo">
  <p> Hello World! </p>
 </div>

 <script>
  if (((window.innerWidth / 100) * 33) < 250) { /* Gets 33% of window width in pixels, tests if it is less than required minimum length (250px) */
  document.getElementById("demo").style.margin = "0 250px 0 0" /* If true, set margin to length in pixels */
  } else {
   document.getElementById("demo").style.margin = "0 33% 0 0" /* If not true, the widow is big enough and percentage length is set */
   }
 </script>
</body>
Related