CSSelector 마스터하기: 예제가 포함된 전체 가이드

王林
풀어 주다: 2024-09-07 00:00:27
원래의
611명이 탐색했습니다.

Mastering CSSelectors: A Complete Guide with Examples

소개

이 기사에서는 작성을 적게 하면서 더 많은 작업을 수행하려는 모든 사람을 위한 매우 강력한 도구인 CSS3 선택기에 대해 설명합니다. 이제 막 시작하든 기술을 연마하든 이 가이드는 기본부터 고급까지 안내합니다.

CSS 기술을 향상할 준비가 되셨나요? 시작해 보세요!

기본 CSS3 선택기

선택기는 HTML 트리에서 특정 요소를 선택하는 데 사용하는 도구입니다. 기본 CSS3 선택기는 이름에서 알 수 있듯이 모든 개발자가 툴킷에 있어야 하는 기본 선택기입니다. 여기에는 Type , Class , ID , UniversalAttribute 선택자가 포함됩니다. 각각에 대해 자세히 알아보겠습니다.

유형 선택기

이러한 선택기는 태그 이름을 기반으로 HTML 요소를 대상으로 합니다. 예를 들어, p { color: blue; }는 모든 단락 요소의 스타일을 파란색으로 지정합니다.

클래스 선택자

이러한 선택기는 클래스 속성을 기반으로 HTML 요소를 대상으로 합니다. 예를 들어, .alert { color: red; } "alert" 클래스가 있는 모든 요소의 스타일을 빨간색으로 지정합니다.

ID 선택기

이러한 선택기는 특정 id 속성이 있는 고유 요소를 대상으로 합니다. 예를 들어 #navbar { background-color: black; }는 ID가 "navbar"인 요소의 스타일을 검정색 배경으로 지정합니다.

범용 선택기

이러한 선택기는 페이지의 모든 요소를 ​​대상으로 합니다. 예를 들어 * { margin: 0; }는 페이지의 모든 요소에서 여백을 제거합니다.

속성 선택기

이 선택자는 속성과 값을 기반으로 요소를 타겟팅합니다. 예를 들어, a[href="https://google.com"] { color: blue; } Google로 연결되는 모든 링크의 스타일을 파란색으로 지정합니다.

짧은 코딩 예제

  • 유형 선택기 : h1 { color: green; } 모든 h1 헤더가 녹색으로 표시됩니다.

  • 유형 선택기 : p { 글꼴 크기: 16px; }는 모든 단락 요소(

    )를 선택하고 글꼴 크기를 16픽셀로 설정합니다.

  • 클래스 선택기 : .info { 글꼴 크기: 18px; }는 "info" 클래스가 있는 모든 요소의 글꼴 크기를 18px로 설정합니다.

  • 클래스 선택기 : .highlight { background-color: yellow; }는 "highlight" 클래스가 있는 모든 요소를 ​​선택하고 배경색을 노란색으로 설정합니다.

  • ID 선택기 : #footer { padding: 20px; }는 ID가 "footer"인 요소에 20px의 패딩을 추가합니다.

  • ID 선택기 : #header { 높이: 60px; }는 ID가 "header"인 요소를 선택하고 높이를 60픽셀로 설정합니다.

  • 범용 선택기 : * { 글꼴 계열: Arial, sans-serif; }는 모든 요소의 글꼴을 Arial로 설정합니다.

  • 범용 선택기 : * { box-sizing: border-box; }는 페이지의 모든 요소를 ​​선택하고 해당 요소의 상자 크기 속성을 "border-box"로 설정합니다. 여기에는 요소의 전체 너비와 높이에 패딩과 테두리가 포함됩니다.

  • 속성 선택기 : img[alt] { border: 2px solid black; } Alt 속성이 있는 모든 이미지에 테두리를 추가합니다.

  • 속성 선택기 : input[type="text"] { width: 100%; } - 이렇게 하면 "텍스트" 유형의 모든 입력 요소가 선택되고 너비가 상위 컨테이너의 100%로 설정됩니다.

의사 클래스 선택기

유사 클래스 선택기는 유형, 속성 또는 클래스가 아닌 문서 구조에서의 상태 또는 위치를 기반으로 요소를 선택하고 스타일을 지정할 수 있는 CSS의 강력한 기능입니다. 이는 역동적이고 반응이 빠른 디자인을 만드는 데 중요한 역할을 합니다.

동적 의사 클래스

동적 의사 클래스에는 사용자 상호 작용에 따라 변경되는 스타일이 포함됩니다. 예를 들어, a:hover { color: red; } 위에 마우스를 올리면 링크 색상이 빨간색으로 변경됩니다.

구조적 의사 클래스

구조적 의사 클래스는 문서 구조에서의 위치에 따라 요소를 선택합니다. 예를 들어, p:first-child {font-weight:bold; } 포함 요소 내에서 첫 번째 단락을 굵게 표시합니다.

부정 의사 클래스

부정 의사 클래스인 :not()은 선택 항목에서 특정 요소를 제외합니다. 예를 들어 div:not(.highlight) { background-color: yellow; } "highlight" 클래스를 제외한 모든 div의 배경색을 노란색으로 변경합니다.

입력 의사 클래스

입력 의사 클래스는 상태에 따라 양식 요소의 스타일을 지정하는 데 사용됩니다. 예를 들어, input:disabled { opacity: 0.5; } 비활성화된 입력 필드의 스타일을 절반 불투명도로 지정합니다.

짧은 코딩 예제

  • 동적 의사 클래스 : a:focus { 개요: 없음; }는 링크를 클릭하거나 키보드를 통해 탐색할 때 링크에서 포커스 윤곽선을 제거합니다.

  • 동적 의사 클래스 : 버튼:활성 { 배경색: 빨간색; } 버튼을 클릭하면 버튼의 배경색이 빨간색으로 변경됩니다.

  • 구조적 의사 클래스 : li:last-child { color: red; } 모든 목록에서 마지막 목록 항목을 빨간색으로 표시합니다.

  • 구조적 의사 클래스 : p:nth-child(2) { color: blue; }는 상위 요소 내의 두 번째 단락을 선택하고 텍스트를 파란색으로 표시합니다.

  • 부정 의사 클래스 : p:not(.no-border) { border: 1px solid black; } "no-border" 클래스가 없는 모든 단락에 테두리를 추가합니다.

  • 부정 의사 클래스 : div:not(#exclude) { border: 1px solid green; } ID가 "exclude"인 모든 div 요소에 테두리를 추가합니다.

  • 의사 클래스 입력 : input:checked { background-color: green; } 체크된 입력 요소의 배경색을 녹색으로 변경합니다.

  • 의사 클래스 입력 : input:valid { border: 2px solid green; }는 유효성 검사 규칙에 따라 모든 유효한 입력 필드에 녹색 테두리를 추가합니다.

유사 클래스 요소

의사 요소 선택기를 사용하면 문서의 특정 부분에 스타일을 지정할 수 있습니다. 요소의 첫 글자나 줄의 스타일을 지정하거나 HTML 요소 앞이나 뒤에 내용을 삽입하는 데 사용할 수 있습니다.

의사 요소 전후

이러한 의사 요소를 사용하면 요소 콘텐츠 앞이나 뒤에 콘텐츠를 삽입할 수 있습니다.

예:

p::before { 
content: "Read this - "; 
color: red;
}
로그인 후 복사

이렇게 하면 모든 단락의 내용 앞에 "Read this -"가 삽입되고 빨간색으로 표시됩니다.

첫 글자와 첫 줄 의사 요소

이러한 의사 요소는 텍스트 블록의 첫 글자나 첫 줄의 스타일을 지정하는 데 사용됩니다.

예:

p::first-letter { 
font-size: 20px; 
color: blue;
}
로그인 후 복사

이렇게 하면 모든 문단의 첫 글자가 20px 크기로 파란색으로 표시됩니다.

짧은 코딩 예

  1. p::after { 내용: "*"; } - 각 단락 뒤에 별표(*)가 추가됩니다.

  2. .warning::before { content: "경고: "; 글꼴 두께: 굵게; 색상: 빨간색; } - "warning" 클래스가 있는 요소의 콘텐츠 앞에 "WARNING: "이 추가됩니다. 텍스트는 굵은 빨간색으로 표시됩니다.

  3. blockquote::first-line { 글꼴 두께: 굵게; } - 이렇게 하면 모든 인용문의 첫 번째 줄이 굵게 표시됩니다.

  4. div::first-letter { text-transform: 대문자; } - 모든 div의 첫 글자를 대문자로 변환합니다.

  5. h1::after { 내용: ""; 색상: 녹색; } - 모든 h1 요소 뒤에 녹색 확인 표시가 추가됩니다.

코드펜 예제

의사 요소와 의사 클래스는 제가 가장 좋아하는 선택자 중 일부이며 이를 실제로 이해하려면 많은 연습을 하는 것이 좋습니다.

다음은 실험해 볼 수 있는 Codepen의 몇 가지 예입니다.

예시 1

튜토리얼

예시 2

튜토리얼

예시 3

튜토리얼

이 예제는 간단해 보이지만 코드를 확인하면 매우 적은 수의 의사 클래스로 만들어졌음을 알 수 있습니다!

결합자 선택기

CSS의 결합자 선택기는 다른 요소와의 특정 관계 기준을 충족하는 특정 요소를 선택하는 강력한 방법입니다. 이러한 선택기를 사용하면 요소가 다른 요소의 하위, 하위 또는 형제인지와 같이 문서 트리에서의 관계를 기반으로 요소를 대상으로 지정할 수 있습니다.

하위 결합자

후손 연결자는 공백으로 표시됩니다. 특정 요소의 자손인 요소를 선택합니다.

예:

div p { color: blue;}
로그인 후 복사

이렇게 하면 모든

의 하위 항목인 요소 요소를 선택하고 텍스트를 파란색으로 지정합니다.

div p { background-color: yellow;}
로그인 후 복사

이렇게 하면 모든

의 하위 항목인 요소 요소를 선택하고 노란색 배경을 지정하세요.

하위 결합자

하위 조합자는 >로 표시됩니다. 특정 요소의 직계 하위 요소를 선택합니다.

예:

div > p { color: blue;}
로그인 후 복사

이렇게 하면 모든

의 직계 하위 요소인 요소 요소를 선택하고 텍스트를 파란색으로 지정합니다.

div > p { border: 1px solid red;}
로그인 후 복사

This will select all

elements that are direct children of a

element, and give them a border.

Adjacent Sibling Combinators

An adjacent sibling combinator is denoted by +. It selects an element that is directly after another specific element.

Example:

div + p { color: blue;}
로그인 후 복사

This will select any

element that is directly after a

element, and color the text blue.

General Sibling Combinators

A general sibling combinator is denoted by ~. It selects elements that are siblings of a certain element.

Example:

div ~ p { color: blue;}
로그인 후 복사

This will select all

elements that are siblings of a

element, and color the text blue.

Advanced CSS3 Selectors

Advanced CSS3 selectors provide more precise targeting capabilities than basic selectors. These include attribute selectors with various matchers and nth-child/nth-of-type selectors.

Attribute Selectors with Various Matchers

Attribute selectors can be used with various matchers to select elements based on specific conditions related to their attributes.

Example:

input[type="text"] { 
color: blue;
}
로그인 후 복사

This will select all input elements with the type attribute of "text" and color the text blue.

Nth-child and Nth-of-type Selectors

The nth-child and nth-of-type selectors are used to select elements based on their position in the parent element.

Example:

p:nth-child(2) { 
color: red;
}
로그인 후 복사

This will select the second child paragraph of its parent element and color the text red.

Short Coding Examples

  1. Attribute Selector with Matcher: a[href^="https"] {font-style: italic;} - This will select all links that have an href attribute that starts with "https" and make the text italic.

  2. Attribute Selector with Matcher: input[type$="text"] {background-color: yellow;} - This will select all input elements that have a type attribute that ends with "text" and give them a yellow background.

  3. Nth-child Selector: li:nth-child(odd) {background-color: grey;} - This will select all odd-numbered list items and give them a grey background.

  4. Nth-of-type Selector: p:nth-of-type(3n) {font-weight: bold;} - This will select every third paragraph and make the text bold.

Best Practices for Using CSS3 Selectors

  1. Use the Right Selector : The key to using CSS3 selectors effectively is to use the right selector for the job. For instance, use class selectors when you want to style a group of elements and ID selectors for unique elements.

  2. Avoid Over-Specification : Over-specifying selectors can make your CSS hard to maintain. Stick to simple selectors as much as possible.

  3. Use Shorthand Properties : Shorthand properties can make your CSS cleaner and easier to read. For example, use margin: 0 auto; instead of margin-top: 0; margin-right: auto; margin-bottom: 0; margin-left: auto;.

  4. Group Selectors : If multiple selectors share the same style declaration, group them together to keep your CSS DRY (Don't Repeat Yourself).

  5. Comment Your Code : Commenting your CSS can help you and others understand what your code does, especially when using complex selectors.

  6. Use Pseudo-classes and Pseudo-elements : These can help you target elements based on their state or position in the document, which can make your CSS more dynamic and responsive.

  7. Keep Specificity Low : Overly specific selectors can lead to specificity wars, making it hard to override styles later. Keep your specificity as low as possible.

  8. Test Across Different Browsers : Different browsers can interpret CSS selectors differently. Always test your CSS across different browsers to ensure consistency.

Conclusion

In conclusion, selectors, ranging from basic type, class, and ID selectors to advanced pseudo-classes, pseudo-elements, and combinators, provide a powerful toolset for styling HTML elements. By understanding and applying these selectors, you can create dynamic, responsive, and aesthetically pleasing websites.

However, it's important to follow best practices such as using the right selector for the job, avoiding over-specification, grouping selectors, and testing across different browsers to ensure the maintainability and consistency of your CSS code.


? Hello, I'm Eleftheria, Community Manager, developer, public speaker, and content creator.

? 이 기사가 마음에 드셨다면 공유해 보세요.

? 모든 링크 | X | 링크드인

위 내용은 CSSelector 마스터하기: 예제가 포함된 전체 가이드의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:dev.to
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
저자별 최신 기사
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!