Max-height on border-boxed div with padding is not set

Extending from Mike's answer, the same can be achieved with a single DOM element & a pseudo element, eg.

html:

<div class="le-div"></div>

css:

div.le-div {
  max-height: 200px;
  /* 👇 only necessary if applying any styles to the pseudo element
     other than padding:

     overflow: hidden;
  */

}

div.le-div::before {
  content: '';
  display: block;
  padding-bottom: 60%;
}

Min-height property defines the height when height is solely dependent on padding only but max-height does not.

Not sure why but now in 2020, min and max css units does nice job as we need.

.classthatshoulddefineheight {
   padding-bottom: min(20%, 60px); 
}

So when 20% becomes greater than 60px then it will be limited to 60px (minimum of them).


I realize this answer comes incredibly late to the party but I was trying to solve this exact same thing today and this question is the first result in Google. I ended up solving it with the below code so hopefully that will help someone out in the future.

First, add an extra inner div:

<div class="control control-max-height">
  <div class="control-max-height-inner">
    Max-height
  </div>
</div>

And set the padding on that while hiding the overflow on the outer div:

.control {
    background: red;
    width: 80%;
    margin: 0 auto 10px;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
}

.control-max-height {
    max-height: 120px;
    overflow: hidden;
}

.control-max-height-inner {
    padding-bottom: 20%;
}

This obviously assumes you're fine with hiding part of the inner element when it overflows. In my case that wasn't a problem because the inner element is just an empty link element to make the whole thing clickable and the outer element just has a centered background image and a border set.

See fiddle: http://jsfiddle.net/UxuEB/7/


The property max-height works on the height of the element and you want to use it on the height and padding-bottom.

I think you are confused by the box-sizing property that it changes the element height to the overal height including the padding top and bottom (also me). But this is not the case as you will see in the jsFiddle example.

An example:

  • The element with content is 100px in height.
  • The max-height is set to 50px (element is now 50px in height).
  • Now we apply the padding-bottom of 100px (more then the height of the element). The padding of 100px is added to the total height of the element making it 150px.

JsFiddle example: clicky

Tags:

Css