gpt4 book ai didi

css - mixins 覆盖媒体查询样式

转载 作者:太空宇宙 更新时间:2023-11-04 05:59:54 25 4
gpt4 key购买 nike

我有一些 JS 功能可以更改 body 元素上的 css 类。基于一次点击,我将我的 body 元素的 css 类更改为以下之一:.font-default.font-medium。字体大

我有以下混入,它们根据 body 元素的类确定元素的字体大小。看起来像这样:

@function rem-calc($size) {
$remSize: $size / 16;
@return #{$remSize}rem;
}

@mixin font-size($size) {
@if $size >= 20 {
font-size: rem-calc($size);
} @else if $size == 18 {
font-size: rem-calc(18);

.font-large & {
font-size: rem-calc(20);
}
} @else {
font-size: rem-calc($size);

.font-medium & {
font-size: rem-calc($size + 2);
}

.font-large & {
font-size: rem-calc($size + 4);
}
}
}

我使用这个mixin的例子如下:

.content {
@include font-size(16);

@media (min-width: 1024px) {
@include font-size(30);
}
}

这是底部链接代码笔上相应的 html 和 css:

<body class="body">
<div class="content">Content</div>
<button class="button">
click to add
</button>
</body>

<script>
const button = document.querySelector('.button')
button.addEventListener('click', () => {
console.log(document.querySelector('.body'))
document.querySelector('.body').classList.add('font-medium');
})
</script>

根据我的规则集(mixin),在桌面版本中,font-size 应该保持不变,因为 size >= 20。但是在实践中,当我单击将类更改为中等的按钮时,它使用样式的“移动”版本并覆盖放置在媒体查询中的样式。

有没有关于特殊性的问题,这样我仍然可以使用这个 mixin,这样移动样式就不会渗透到媒体查询中嵌套的样式中?

如果不是,这个问题可能有什么不同的解决方案?

这里有一支笔可以说明问题。单击按钮时,我希望字体保持不变。 https://codepen.io/rv-akim/pen/WVJpWj

最佳答案

你可以清楚地看到.font-medium .content正在覆盖 .content由于前者更具体,尽管 .content在媒体查询中。

更新你的代码,让你的字体大小的正常状态使用一个类

@mixin font-size($size) {
@if $size >= 20 {
.normal & {
font-size: rem-calc($size);
}
} @else if $size == 18 {
.normal & {
font-size: rem-calc(18);
}
.font-large & {
font-size: rem-calc(20);
}
} @else {
.normal & {
font-size: rem-calc($size);
}

.font-medium & {
font-size: rem-calc($size + 2);
}

.font-large & {
font-size: rem-calc($size + 4);
}
}
}

.content {
@include font-size(16);

@media (min-width: 1024px) {
@include font-size(30);
}
}

将类 normal 添加到您的 body 标签

<body class="body normal">

基本上,在您只声明字体大小规则的地方,我用 .normal & {} 包裹了它

如果你学会了使用 Inspector,以后会省去很多麻烦

关于css - mixins 覆盖媒体查询样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57418943/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com