194

max-height如果之前在某些 CSS 规则中设置了该属性,如何将其重置为默认值?这不起作用:

pre {
  max-height: 250px;
}

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

5 回答 5

358

将其重置为none

pre {
  max-height: 250px;
}

pre.doNotLimitHeight {
  max-height: none;
}

参考

于 2012-12-21T10:14:33.333 回答
29

您可以使用以下 css 清除 max-height 属性:

max-height:none; 
于 2012-12-21T10:15:04.817 回答
7

您可以使用

max-height: unset;

如果您从其父级继承(将作为关键字继承),它将重置为其继承值,如果您不继承,它将重置为其初始值(将作为关键字初始)。

于 2019-11-06T14:29:48.787 回答
3

请注意,如果您使用 JavaScript 来设置元素的样式,例如$el.style.maxHeight = '50px';using$el.style.maxHeight = 'none';不会“重置”或“删除” 50px,它只会覆盖它。这意味着,如果您尝试“重置”使用$el.style.maxHeight = 'none';它的元素的最大高度,则会将该none值应用于max-height元素的属性,覆盖max-heightCSS 选择规则中与该元素匹配的任何其他有效属性。

一个例子:

样式.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;
  }
}

您可以随心所欲地找到StyleSheetCssRule对象,但对于一个简单的应用程序,我相信以上就足够了。

很抱歉将此作为答案,但我没有 50 个代表,所以我无法发表评论。

干杯。

于 2017-04-08T03:45:39.160 回答
1

使用任一

max-height: none;

或者

max-height: 100%;

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

于 2018-04-19T18:22:16.760 回答