CSS에는 가상 요소(:pseudo-element)와 가상 클래스(:pseudo-class)가 있다. 이것들을 사용해서 html 문서의 수정 없이 CSS만으로 디자인적 요소를 추가할 수 있어 html 문서에 쓸데없는 태그를 사용하여 화면 리더기 등에 쓸데없는 정보가 읽히거나 불필요한 클래스를 남발해 코드 가독성을 낮추지 않게 한다.
선택자:가상클래스 { property: value; }
앵커 가상 클래스에서 가장 자주 쓰이는 패턴이다. :link는 아직 방문하지 않은 링크를 나타낸다. 다음을 사용해서 아직 방문하지 않은 링크를 파란색으로, 방문한 링크는 밑줄 없이 보라색으로 표현할 수 있다.
/* 클릭 전 링크 */
a:link {
color: blue;
}
/* 클릭 후 링크 */
a:visited {
color:purple;
text-decoration: none;
}
/* 커서가 해당 요소위에 있을때 */
a:hover {
color: red;
}
/* 클릭한 상태(눌리는중) */
a:active {
color: gray;
}
입력창 키보드 입력
/* 키보드를 입력가능 커서 */
input:focus {
color: yellow;
}
여러개의 같은 태그요소들에 따로 CSS를 주기 위해 클래스를 추가할 필요가 없다
:first-child : li 중 첫번쩨 요소에 해당 CSS를 적용한다.
:last-child : li 중 마지막에 해당 CSS를 적용한다.
:nth-child(n) : li 중 n번쩨 요소에 해당 CSS를 적용한다. (odd,even)
ol li:first-child {
border-top: none;
}
ol li:last-child {
border-top: none;
}
ol li:nth-child(2) {
border-top: none;
}
가상 클래스가 실제로 존재하는 요소에 클래스 추가 없이 디자인을 입히기 위한 것이라면, 가상 요소는 아예 실제로 존재하지 않는 요소를 만들게 해준다.
<label class="is-required" for="name">Name</label>
<input type="text" />
body {
font-family: 'Franklin Gothic Medium', 'Arial Narrow', Arial, sans-serif;
background: #333;
color: #fff;
}
.is-required::before {
content: '⭐';
color: white;
padding-right: 2px;
}
.is-required::after {
content: '⭐';
color: white;
padding-left: 2px;
}
example1 의 label, input 태그는 주석처리하고 section 위에
아래의 header 태그를 넣습니다.
<header>
<h1>Hello World</h1>
<p>
Lorem, ipsum dolor sit amet consectetur adipisicing elit. Ipsam, hic!
</p>
</header>
header {
display: ?;
flex-direction: ?;
justify-content: ?;
align-items: ?;
text-align: center;
height: 100vh;
}
header h1 {
font-size: 6rem;
margin: 1rem;
}
header::before {
content: '';
background: url('https://source.unsplash.com/1600x900/?nature,water') no-repeat center center/cover;
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: -1;
opacity: 0.5;
}