CSS之:focus-within自身或某個後代focus的僞類

1. 什麼是:focus-within?

:focus-within 是一個CSS 僞類 ,表示一個元素或其後代元素獲得焦點

在表單中,這個僞類非常有用。

2. 兼容性

需要注意的是,IE不支持
在這裏插入圖片描述

3. 例子

看下面這個例子,在input被選中的時候,隱藏*,並把整行變爲灰色。
在這裏插入圖片描述
demo: https://jsfiddle.net/6epmr4u8/

<form>
  <div class="field">
    <span>name:</span>
    <input type="text">
  </div>
  <div class="field">
    <span>age:</span>
    <input type="text">
  </div>
</form>

有field類的div在後代元素input被focus時,顏色發生變化,*的僞類也不顯示。

.field{
  padding: 10px;
  &:focus-within{
    background-color: #f0f0f0;
    &::after{
      display: none;
    }
  }
  &::after{
    content:'*';
    color: red;
  }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章