擬似要素
Style::pseudo は、::before、::placeholder、リスト項目のマーカーのように、それ自体は要素ではない要素の一部にスタイルを付けます。
要素の一部に付ける宣言
Style::pseudo(fn pseudo(self, element: PseudoElement, style: Style) -> Style)は、style の宣言を要素の擬似要素に付けます。PseudoElement は MDN の CSS データから生成しており、Before、After、Placeholder、Marker、Selection、FileSelectorButton、Backdrop など、標準の擬似要素を持っています。
use hypersig::html::{a, input, li, ul};
use hypersig::style::value::{Color, quoted};
use hypersig::style::{PseudoClass, PseudoElement, Style};
use hypersig::{Page, SafeUrl, Signals};
use serde::{Deserialize, Serialize};
#[derive(Signals, Serialize, Deserialize)]
struct Search {
query: String,
}
// `::after` is drawn only when `content` is set.
let more = a::<Search>()
.href(SafeUrl::new("/docs"))
.css(
Style::new()
.pseudo(PseudoElement::After, Style::new().content(quoted(" →")))
// `:hover::after`: the pseudo-class is tested on the link.
.on(
PseudoClass::Hover,
Style::new().pseudo(PseudoElement::After, Style::new().color(Color::RED)),
),
)
.text("More");
let field = input::<Search>()
.bind(Search::query())
.css(Style::new().pseudo(PseudoElement::Placeholder, Style::new().color(Color::GRAY)));
// `::marker` is the bullet of a list item.
let step = Style::new().pseudo(PseudoElement::Marker, Style::new().color(Color::hex(0x0025_63eb)));
let steps = ul::<Search>().child(li().css(step).text("Install"));リンク、入力欄、リスト項目をそれぞれ .more、.field、.step と書くと、ブラウザが適用するのは次の CSS です。
.more::after { content: " →" }
.more:hover::after { color: red }
.field::placeholder { color: gray }
.step::marker { color: #2563eb }擬似要素の中の擬似クラス
擬似クラスは常に要素に対して適用され、擬似要素には適用されません。pseudo(After, Style::new().on(Hover, ..)) と on(Hover, Style::new().pseudo(After, ..)) はどちらも :hover::after になり、ポインタが要素の上にある間に当てはまります。
擬似要素は条件ではない
on は Condition を受け取りますが、PseudoElement は Condition に変換できません。擬似要素は要素の一部であって、要素の状態ではないからです。on に渡すとコンパイルエラーになります。
use hypersig::style::value::quoted;
use hypersig::style::{PseudoElement, Style};
// error[E0277]: the trait bound `Condition: From<PseudoElement>` is not satisfied
let more = Style::new().on(PseudoElement::After, Style::new().content(quoted(" →")));擬似要素は 1 段まで
CSS には擬似要素の擬似要素がないので、渡されたスタイルがすでに擬似要素に宣言を付けていると pseudo はパニックします。パニックはスタイルを組み立てる場所で起きるので、ページを組み立てるテストで見つかります。
use hypersig::style::value::Color;
use hypersig::style::{PseudoElement, Style};
// Panics: a pseudo-element holds no pseudo-element
let style = Style::new().pseudo(
PseudoElement::Before,
Style::new().pseudo(PseudoElement::Marker, Style::new().color(Color::RED)),
);型では検査しないこと
::beforeと::afterはcontentを設定したときだけ描画されます。設定しなければ、ほかの宣言はコンパイルが通っても何も表示されません。- 要素にその擬似要素があるかどうかは検査しません。
<div>の::placeholderや、リスト項目でない要素の::markerは何にも適用されません。 - 一部の擬似要素は限られたプロパティしか受け付けません。
::markerが受け付けるのはcolor、content、フォントのプロパティなどで、それ以外はブラウザが無視します。
次に読むページ
メディアクエリではビューポートの幅やユーザーの設定に応じてスタイルを適用します。content の値を作る quoted は URL と文字列で説明しています。