# :focus 정리

## :focus&#x20;

마우스 또는 키보드로 포커스가 된 상태&#x20;

## :focus-visible&#x20;

&#x20;마우스가 아닌 키보드로 포커스가 된 상태&#x20;

{% hint style="info" %}
마우스로 포커스 된 상태는 아래와 같이 사용할 수 있다.&#x20;

```
:not(:focus-visible)
```

{% endhint %}

### example&#x20;

```css
/* 기본 포커스 상태 */
*:focus {
  outline: none;
  box-shadow: 0 0 0 0.3rem ${getColor('focusVisible')};
}

/* 마우스로 포커스 한 상태 */
*:not(:focus-visible) {
  outline: none;
  box-shadow: none;
}

/* 키보드로 포커스 한 상태 */
*:focus-visible {
  outline: none;
  box-shadow: 0 0 0 0.3rem ${getColor('focusVisible')};
}
```

{% hint style="warning" %}
주의 !&#x20;

`:focus` 상태를 설정하지 않으면 아래의 상태는 적용되지 않는다. 즉, 아래의 두 상태만 따로 설정할 수 없다.&#x20;

```css
:not(:focus-visible)
:focus-visible
```

{% endhint %}

## :focus-within&#x20;

&#x20;본인 또는 자식이 포커스를 받으면 `:focus-within`이 설정된 요소에 스타일이 적용된다.&#x20;

* `<input>`, `<label>`에 포커스가 되었을 때 `<form>`에 강조를 주고 싶을 때 사용할 수 있다.&#x20;
* `::before`, `::after`와 같은 가상 요소에 focus 상태 시 스타일을 주고 싶을 때 사용할 수 있다.&#x20;

### example

&#x20;아래와 같은 경우 input에 포커스가 되었을 때&#x20;

```markup
<form>
  <label for="name">이름</label>
  <input id="name" type="text">
</form>
```

```css
form:focus-within {
  background: #ff8;
  color: black;
}
```

{% hint style="info" %}
자식 요소가 :focus-visible인 경우에만 :focus-within 스타일을 적용하는 방법&#x20;

```css
.input-group:has(:focus-visible):focus-within {
  outline: 4px solid hotpink;
}
```

{% endhint %}

## reference

* [:focus-within](https://developer.mozilla.org/ko/docs/Web/CSS/:focus-within) → 공식 문서
* [:focus vs :focus-within](https://tenmilesquare.com/focus-vs-focus-within/) → 블로그&#x20;
* [:focus-visible-within, the missing pseudo-class](https://larsmagnus.co/blog/focus-visible-within-the-missing-pseudo-class)
