0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

CSSの小技集(トリミング、疑似要素、疑似クラス)

Last updated at Posted at 2022-02-19

覚えてたら便利かもっていうCSS!

画像をトリミングする

この背景画像を
image.png

こんな感じでアスペクト比を保ったまま横幅いっぱいに拡大したい。
image.png

object-fitobject-positionを使用。

html
<div className={styles.mainContainer}>
  <img className={styles.mainBg} src={main_bg} alt="メイン背景" />
</div>
css
.mainContainer {
  .mainBg {
    width: 100%;
    object-fit: none;
    object-position: 50% 0%; // 左右 上下
  }
}

object-positionの値で背景画像位置を調整する。
image.png

擬似要素を使う

特定の部分にのみ、CSSを当てることができる。

html
<>
    <p className={styles.first}>
      一段落目の説明
      <p>あいうえお</p>
      <p>かきくけこ</p>
      <p>さしすせそ</p>
    </p>
    <p className={styles.second}>
      二段落目の説明
      <p>abcde</p>
      <p>fghij</p>
    </p>
</>
css
.first::first-letter {
  // 要素の一文字目にスタイルを適用
  color: red;
}

.second::first-line {
  // 要素の一行目にスタイルを適用
  color: blue;
}

image.png

参考
擬似要素

擬似クラスを使う

特定の状態を指定し、CSSを当てることができる。

ボタンのbackground-color: #fff;のみ設定。
「押せそう」感がない、、、
タイトルなし.gif

html
<button className={styles.testButton}>test</button>
css
.testButton {
  background-color: #fff;
  cursor: pointer;
}
.testButton:hover {
  // カーソルが当たった時にスタイルを適用
  background-color: gray;
}

ついでにcursor: pointer;も追加してさらに「押せそう」感を出しました。

タイトルなし.gif

参考
擬似クラス

0
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?