当前位置: 动力学知识库 > 问答 > 编程问答 >

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

问题描述:

We use the percentage trick on paddings to keep aspect ratio to a div when the user scales his window. Like this:

.div {

background: red;

width: 80%;

margin: 0 auto 10px;

-webkit-box-sizing: border-box;

box-sizing: border-box;

padding-bottom: 20%;

}

Now we would like to be able to set a maximum height to this div. Because the height of the div is determined by the padding on the div we would need the div to be border-boxed. So far so good. When trying to use a min-height on the div, this works. The max-height on this div however does not work for some reason.

.div {

max-height: 60px;

}

I created a fiddle to show you what i mean: http://jsfiddle.net/UxuEB/3/.

Tested this on Chrome, FF and IE. Can somebody tell me what I'm doing wrong or why this doesn't work as expected?

网友答案:

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

网友答案:

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/

分享给朋友:
您可能感兴趣的文章:
随机阅读: