首页 > 解决方案 > CSS 覆盖样式,但如果嵌套则恢复为原始样式

问题描述

我为我的 Vue 应用程序创建了一个非常基本的模式来显示消息。我想为包含其他 Vue 组件的模态重用基本逻辑和样式,所以我在包装器中添加了一个类来更改它的样式。这个带有组件的模式可以有其他消息模式,然后应该再次使用默认样式。在不重复嵌套样式中的基本样式的情况下实现此目的的最佳方法是什么:

.modal-mask {
    background-color: rgba(0, 0, 0, 0.5);
    display: table;
    position: fixed;
    left: 0;
    top: 0;
    height: 100%;
    width: 100%;
    transition: opacity 0.3s ease;
    z-index: 100;
}
.modal-wrapper {
    display: table-cell;
}
.modal-content {
    background-color: #fff;
    border: 1px solid #333333;
    margin: 10vh auto;
    max-height: 90vh;
    padding: 20px;
    overflow-y: auto;
    transition: all 0.3s ease;
    width: 400px;
}
.modal-dynamic .modal-content {
    width: fit-content;
    padding: 0;
}
/* is there a better way to reset it to the .modal-content style defined first */
.modal-content .modal-content {
    padding: 20px;
    width: 400px;
}
<div class="modal-mask modal-dynamic" aria-role="dialog">
    <div class="modal-wrapper">
        <div class="modal-content">
            <SOME HTML MARKUP>
            <div class="modal-mask" aria-role="dialog">
                <div class="modal-wrapper">
                    <div class="modal-content">
                        Some message
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

在这种情况下,它只有两个属性,但如果有更多,它会变得麻烦且难以维护。所以“重置”会很棒。

标签: css

解决方案


根据您提供的 html,您可以简单地使用:.modal-dynamic > .modal-wrapper > .modal-content

演示

.modal-dynamic > .modal-wrapper > .modal-content {
    width: fit-content;
    padding: 0;
}
.modal-mask {
    background-color: rgba(0, 0, 0, 0.5);
    display: table;
    position: fixed;
    left: 0;
    top: 0;
    height: 100%;
    width: 100%;
    transition: opacity 0.3s ease;
    z-index: 100;
}
.modal-wrapper {
    display: table-cell;
}
.modal-content {
    background-color: #fff;
    border: 1px solid #333333;
    margin: 10vh auto;
    max-height: 90vh;
    padding: 20px;
    overflow-y: auto;
    transition: all 0.3s ease;
    width: 400px;
}
/*.modal-dynamic .modal-content {
    width: fit-content;
    padding: 0;
}*/
/* is there a better way to reset it to the .modal-content style defined first */
/*.modal-content .modal-content {
    padding: 20px;
    width: 400px;
}*/
<div class="modal-mask modal-dynamic" aria-role="dialog">
    <div class="modal-wrapper">
        <div class="modal-content">
            <!--<SOME HTML MARKUP>-->
            <div class="modal-mask" aria-role="dialog">
                <div class="modal-wrapper">
                    <div class="modal-content">
                        Some message
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>


推荐阅读