2025-05-28 10:00:00

如何取消最大高度?

我如何重置最大高度属性为默认值,如果它已经在一些CSS规则之前设置?这行不通:

pre {
  max-height: 250px;
}

pre.doNotLimitHeight {
  max-height: auto; // Doesn't work at least in Chrome
}

重置为none:

pre {
  max-height: 250px;
}

pre.doNotLimitHeight {
  max-height: none;
}

参考


你可以使用下面的css来清除max-height属性:

max-height:none; 

注意,如果使用JavaScript对元素进行样式化,比如$el.style。maxHeight = '50px';使用el.style美元。maxHeight = 'none';不会“重置”或“移除”50px,它会简单地覆盖它。这意味着如果你试图使用$el.style“重置”元素的最大高度。maxHeight = 'none';它会将none值应用到元素的max-height属性,覆盖CSS选择规则中匹配该元素的任何其他有效的max-height属性。

一个例子:

styles.css

.set-max-height { max-height: 50px; }

main.js

document.querySelectorAll('.set-max-height').forEach($el => {
  if($el.hasAttribute('data-hidden')){
    $el.style.maxHeight = '0px'; // Set max-height to 0px.
  } else {
    $el.style.maxHeight = 'none'; // 'Unset' max-height according to accepted answer.
});

要真正“取消”一个内联样式,你应该使用$el.style.removeProperty('max-height');

要对整个样式规则而不仅仅是单个元素进行修改,你应该首先找到你想修改的规则,然后调用该规则上的removeProperty函数:

for(let i = 0; i < document.styleSheets[0].cssRules.length; ++i){
  if(document.styleSheets[0].cssRules[i].selectorText == '.set-max-height'){
    document.styleSheets[0].cssRules[i].style.removeProperty('max-height');
    break;
  }
}

您可以找到样式表和CssRule对象,但是对于一个简单的应用程序,我相信上面的内容就足够了。

抱歉把这个作为一个答案,但我没有50个代表,所以我不能评论。

欢呼。


使用

max-height: none;

or

max-height: 100%;

注:第二个是相对于包含块的高度。


你可以使用

max-height: unset;

如果你从其父继承一个属性(将作为关键字继承),它将重置为其继承的值,如果你没有继承它将重置为其初始值(将作为关键字initial)。