如何取消最大高度?

我如何重置max-height属性为其默认值,如果它已经在一些CSS规则之前设置?这行不通:

pre {
max-height: 250px;
}


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

将其重置为none:

pre {
max-height: 250px;
}


pre.doNotLimitHeight {
max-height: none;
}

参考< a href = " https://developer.mozilla.org/en-US/docs/CSS/max-height " > < / >

你可以使用下面的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;
}
}

你可以找到你想要的StyleSheetCssRule对象,但对于一个简单的应用程序,我相信上面的就足够了。

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

欢呼。

使用

max-height: none;

max-height: 100%;

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

你可以使用

max-height: unset;

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