簡體   English   中英

SCSS 目標類和偽選擇器同時進行

[英]SCSS target classes and pseudo selectors simultaneously

我正在編寫一個庫,我想為所有按鈕設置樣式。

HTML

<div>
  <p>Buttons</p>
  <button>Button</button>
  <button class="r1">Button</button>
</div>

<div>
  <p>File inputs</p>
  <input type="file" />
  <input type="file" class="r1" />
</div>

SCSS

button,
input[type=file]::file-selector-button {
  background: #81ecec;
  border: 2px solid #00cec9;
  &.r1{
    background: red;
  }
}

此代碼處理為:

button.r1,
input[type=file]::file-selector-button.r1 {
  background: red;
}

[這是無效的,不起作用]

是否有我可以使用的 mixin 或方法,以便我可以將類僅放在父選擇器上,而不會失控? 我打算有多個類( primarysecondarylargesmall ),我不想寫

button.r1,
input[type=file].r1::file-selector-button{
  ...
}

button.large,
input[type=file].large::file-selector-button{
   ...
}

button.small,
input[type=file].small::file-selector-button{
   ...
}

我想不出針對父input[type="file"]

這個codepen里面有第一個例子,因為它不是有效的 CSS background: red沒有生效:

https://codepen.io/EightArmsHQ/pen/VwxwPGM/139933ae274200149b84afdb726478c5?editors=1100

嘗試 1

目前我正在使用這樣的mixin:

@mixin button{
  background: var(--button-primary);
  color: #fff;
  text-decoration: none;
  border: none;
  display: inline-block;
  padding: 4px 8px;
}

@mixin button-r1{
  border-radius: 3px;
}

button,
.button,
input[type="submit"],
input[type="reset"]{
  @include button;
  &.r1{
    @include button-r1;
  }
}

input[type=file]{
  &::file-selector-button{
    @include button;
  }
  &.r1::file-selector-button{
    @include button-r1;
  }
}

好處是我不需要一遍又一遍地重復相同的 styles,但是我覺得必須有更好的方法來創建一個以某種方式插入 class 的 mixin。

嘗試 2

使用類名作為參數效果很好,但是我失去了嵌套規則的能力,這是一種恥辱,也是我最喜歡的 SCSS 部分之一。

@mixin buttonAndFileInputs($classname: "") {
  button#{$classname},
  .button#{$classname},
  input[type="submit"]#{$classname},
  input[type="reset"]#{$classname}, 
  input[type="file"]#{$classname}::file-selector-button {
    @content;
  }
}


@include buttonAndFileInputs {
  background: var(--button-primary);
  color: #fff;
}

@include buttonAndFileInputs(".r1") {
  border-radius: 3px;
}

我不是 100% 清楚你想要做什么

但我認為如果你將你的 codepen 編輯到這個 scss

button,
input[type=file] {
  background: #81ecec;
  border: 2px solid #00cec9;
  &.r1{
    background: red;
  }
}

::file-selector-button {
  background: inherit;
  border: inherit;
}

這將得到你正在尋找的東西

編輯以添加說明:這將使file-selector-button遵循input[type=file]backgroundborder屬性。
這意味着file-selector-button將匹配輸入背景的 rest。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM