【发布时间】:2012-12-21 10:12:21
【问题描述】:
如果之前在某些 CSS 规则中设置了 max-height 属性,如何将其重置为默认值?这不起作用:
pre {
max-height: 250px;
}
pre.doNotLimitHeight {
max-height: auto; // Doesn't work at least in Chrome
}
【问题讨论】:
标签: css
如果之前在某些 CSS 规则中设置了 max-height 属性,如何将其重置为默认值?这不起作用:
pre {
max-height: 250px;
}
pre.doNotLimitHeight {
max-height: auto; // Doesn't work at least in Chrome
}
【问题讨论】:
标签: css
【讨论】:
min-height(none 是不允许的,会导致该值未被覆盖)。
min-height 的默认值为 0,但由于 CSS 中没有“无限”,max-height 默认为 none。
您可以使用以下 css 清除 max-height 属性:
max-height:none;
【讨论】:
你可以使用
max-height: unset;
如果您从其父级继承(将作为关键字继承)将属性重置为其继承值,如果您不继承,它将重置为其初始值(将作为关键字初始)。
【讨论】:
unset 在 IE11 中不受支持,如下所示:caniuse.com/css-unset-value max-height: none 是正确答案。
请注意,如果您使用 JavaScript 设置元素的样式,如使用 $el.style.maxHeight = 'none'; 的 $el.style.maxHeight = '50px'; 将不会“重置”或“删除”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;
}
}
您可以随心所欲地找到StyleSheet 和CssRule 对象,但对于一个简单的应用程序,我相信以上就足够了。
很抱歉将其作为答案,但我没有 50 个代表,所以我无法发表评论。
干杯。
【讨论】:
使用任一
max-height: none;
或
max-height: 100%;
注意:第二个是相对于包含块的高度。
【讨论】: