Skip to main content

[掘竅] 小技巧 CSS Tips

目錄#

[TOC]

避免按鈕被 Focus#

使用 JavaScript 的 click 事件:

const button = document.querySelector('button');button.addEventListener('click', (e) => e.target.blur());

Pseudo-classes#

child#

keywords: :first-child, :last-child, :nth-child(), :nth-last-child(), :only-child#

使用這幾個選擇器時,實際上是先看 first-child, last-child, 或 n 這個元素,接著才來看它符不符合所選擇的 tag 或 class。

舉例來說:

<!-- 先看 div 裡的 last-child,在看是不是 <p> --><div>  <p>    Lorem ipsum is placeholder text commonly used in the graphic, print, and publishing industries    for previewing layouts and visual mockups.  </p>  <p>    Lorem ipsum is placeholder text commonly used in the graphic, print, and publishing industries    for previewing layouts and visual mockups.  </p></div>
<div>  <p>    Lorem ipsum is placeholder text commonly used in the graphic, print, and publishing industries    for previewing layouts and visual mockups.  </p>  <h4>    Lorem ipsum is placeholder text commonly used in the graphic, print, and publishing industries    for previewing layouts and visual mockups.  </h4></div>
/** * 先看 div 裡的 last-child ,接著,如果是 <p> ,才套用**/div p:last-child {  background-color: steelblue;}
/** * 先看 div 裡所有 last child ,接著,因為沒有額外條件,表示全選(*) * 所以全部的 <div> 中的 last-child 都會套用**/div :last-child {  background-color: steelblue;}
/** * 如果使用的是 nth-of-type ,則是會選取 <div> 當中的最後一個 <p>**/div p:last-of-type {  background-color: steelblue;}

type#

keywords: first-of-type, last-of-type, :nth-last-of-type(), :nth-of-type(), :only-of-type#

nth-child-selector @ CodePen demo @ JSFiddle

參考#