有关完整的css / html摘录,请参阅:https://jsfiddle.net/menelaosbgr/jbnsd9hc/1/
我有以下特定的2个定义:
/* Dropdown Content (Hidden by Default) */
.dropdown-content {
display: none;
position: absolute;
background-color: #f9f9f9;
min-width: 120px;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
z-index: 1;
bottom: 0px;
right: 0px;
}
@media screen and (min-width: 480px) {
.dropdown-content {
display: none;
position: absolute;
background-color: #f9f9f9;
min-width: 120px;
box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
z-index: 1;
bottom: 0px;
right: -50px;
}
}
我想重构代码以使其更优雅。我尝试了以下但是没有用:
/* Dropdown Content (Hidden by Default) */
.dropdown-content {
display: none;
position: absolute;
background-color: #f9f9f9;
min-width: 120px;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
z-index: 1;
bottom: 0px;
right: 0px;
@media screen and (min-width: 480px) {
bottom: 0px;
right: -50px;
}
}
澄清:如何重写以上内容以免重复?
答案 0 :(得分:2)
Validate, validate, validate。你根本无法在CSS中做到这一点。规则集不能包含媒体查询。
你可以使用SASS执行此操作,然后可以将其转换为CSS。
答案 1 :(得分:1)
只需加上我的2美分价值,这里有一个你选择的例子:
<强> CSS:强>
/* Dropdown Content (Hidden by Default) */
.dropdown-content {
display: none;
position: absolute;
background-color: #f9f9f9;
min-width: 120px;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
z-index: 1;
bottom: 0px;
right: 0px;
}
您希望在不同分辨率上更改的任何在媒体查询中更改不每个媒体资源:
@media screen and (min-width: 480px) {
.dropdown-content {
right: -50px;
}
}
<强> SASS / SCSS:强>
/* Dropdown Content (Hidden by Default) */
.dropdown-content {
display: none;
position: absolute;
background-color: #f9f9f9;
min-width: 120px;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
z-index: 1;
bottom: 0px;
right: 0px;
@media(min-width: 480px){
right: -50px;
}
@media(min-width: 768px){
right: -25px;
}
}
答案 2 :(得分:0)
你可以简单地删除重复。只需保持不同之处:
/* Dropdown Content (Hidden by Default) */
.dropdown-content {
display: none;
position: absolute;
background-color: #f9f9f9;
min-width: 120px;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
z-index: 1;
bottom: 0px;
right: 0px;
}
@media screen and (min-width: 480px) {
.dropdown-content {
right: -50px;
}
}