본문 바로가기
Front-end/Web

CSS - 선택자, 상속

by 안녕주 2021. 2. 2.

1. 기본 문법

- 기본형태

선택자 { 
	속성 : 속성값; 
	속성 : 속성값;
}

- 선택자의 역할 

  • HTML의 원하는 요소에 CSS의 속성과 값이 적용

- 속성과 값의 역할

  • 검색된 대상에 지정될 CSS 명령

- CSS의 주석

/*  Comment  */

 


2. 선언방식

-1) 인라인(in-line)방식 : HTML 요소(태그)의 'style' 속성에 직접 작성하는 방식

<div style="color:red; font-size:20px;>Hello</div>

 

-2) 내장(embedded) 방식 : HTMl <style></style> 안에 작성하는 방식

<head>
	<style>
    	div {
        	color:red;
            font-size:10px;
        }
	</style>
</head>

 

-3) 링크(link) 방식 : HTML <link>를 이용하여 외부 문서로 CSS를 불러와 적용하는 방식

<link rel="stylesheet" href="./main.css"> <!-- ./생략가능, 상대경로-->
div{
	color: red;
    font-size: 10px;
}

 

-4) @import 방식 : CSS @import를 이용하여 외부 문서로 CSS를 불러와 적용하는 방식

  • 즉 import는 CSS가 CSS를 불러오는 방식
  • 직렬 호출방식, 시간이 오래 걸린다.
<head>
	<link rel="stylesheet" href="css/common1.css"> <!-- 외부에 있는 CSS파일 불러오기-->
</head>

<body>
	<div>HELLO</div>
</body>
/* @ = import  */
/* common1.css */
@import url ("./common2.css*/); /*외부에 있는 CSS파일 불러오기*/
/* common2.css */
div {
	color: red;
    font-size : 20px;
}

 


3. 기본 선택자(중요✨✨✨)

-1) 전체 선택자 : (요소 내부의) 모든 요소를 선택 : *

* {
	color: red;
}
<div>
	<ul>
    	<li>사과</li>
        <li>딸기</li>
    </ul>
    <div>당근</div>
</div>

 

-2) 태그 선택자 : 태그이름에 해당하는 요소 선택

li {
	color : red;
}
<div>
    <ul>
    	<li>사과</li>
        <li>딸기</li>
    </ul>
    <div>당근</div>
</div>

 

-3) 클래스 선택자 : HTML class속성의 값을 가진 요소 선택, 무난하게 널리 사용 : .

.orange {
	color: orange;
}
<div>
    <ul>
    	<li>사과</li>
        <li>딸기</li>
        <li class="orange">오렌지</li>
    </ul>
    <div>당근</div>
    <p>토마토</p>
    <span class="orange">오렌지</span>
</div>

 

-4) 아이디 선택자 : HTML id속성의 값을 가진 요소 선택, 고유하고 중요한 곳에 사용 : #

#orange {
	color: orange;
}
<div>
    <ul>
    	<li>사과</li>
        <li>딸기</li>
        <li id="orange" class="orange>오렌지</li>
    </ul>
    <div>당근</div>
    <p>토마토</p>
    <span class="orange">오렌지</span>
</div>

 


4. 복합 선택자

-1) 일치 선택자 : 선택자 두가지(E,F)를 동시에 만족하는 요소 선택 : EF

span.orange {  /*태그선택자 + 클래스선택자*/
	color: orange;
}
<div>
    <ul>
    	<li>사과</li>
        <li>딸기</li>
        <li id="orange" class="orange>오렌지</li>
    </ul>
    <div>당근</div>
    <p>토마토</p>
    <span class="orange">오렌지</span>
</div>

 

-2) 자식 선택자 : 요소 E의 자식요소 F를 선택 : E > F

ul > .orange {  /*태그 선택자 > 클래스 선택자*/
	color: orange;
}
<div>
    <ul>
    	<li>사과</li>
        <li>딸기</li>
        <li id="orange" class="orange>오렌지</li>
    </ul>
    <div>당근</div>
    <p>토마토</p>
    <span class="orange">오렌지</span>
</div>

 

-3) 후손(하위) 선택자 : 요소 E의 후손(하위) 요소 F를 선택 : E F

/*띄어쓰기가 선택자의 기호로 사용*/
div .orange{
	color: orange;
}
<div>
    <ul>
    	<li>사과</li>
        <li>딸기</li>
        <li id="orange" class="orange>오렌지</li>
    </ul>
    <div>당근</div>
    <p>토마토</p>
    <span class="orange">오렌지</span>
</div>
  • 본인 아래  요소들 = 후손(하위) 요소
  • 본인 위 요소들 = 조상(상위) 요소
  • 부모, 자식, 형제 요소

-4) 인접 형제 선택자 : 요소 E의 다음 형제 요소 F 하나만 선택 : E + F

/orange + li {
 	color : orange;
}
<ul>
    <li>사과</li>
    <li>딸기</li>
    <li class="orange">오렌지</li>
    <li>망고</li> <!--망고가 선택-->
    <li>사과</li>
</ul>

 

-5) 일반 형제 선택자 : 요소 E의 다음 형제 요소 F 모두 선택 : E ~ F

.orange ~ li {
	color: orange;
}
<ul>
    <li>사과</li>
    <li>딸기</li>
    <li class="orange">오렌지</li>
    <li>망고</li> <!--망고, 사과 선택-->
    <li>사과</li>
</ul>

 


5. 가상클래스 선택자 - hover, active, focus

-1) hover : 요소 E에 마우스(포인터)가 올라가 있는 동안에만 요소E 선택 : E:hover

<a href="https://google.com">Google!</a>
<div class="box"></div>
a:hover{
  font-weight: bold;
  font-size: 20px;  
}
.box{
  width:100px;
  height:100px;
  background: tomato;
  transition: 0.4s;
}
.box:hover {
  width: 200px;
}

 

-2) active : 요소 E를 마우스로 클릭하는 동안에만 E선택 : E:active

<div class="box"></div>
.box{
  width:100px;
  height:100px;
  background: tomato;
  transition: 0.4s;
}
.box:active {
  width: 200px;
  background: yellowgreen;
}

 

-3) focus : 요소 E가 포커스 된 동안에만 E선택, 대화형 콘텐츠에서 사용가능(input, img, tabindex) : E:focus

<input type="text">
input {
  width:100px;
  outline: none;
  border: 1px solid lightgray;
  padding: 5px 10px;
  transition: 0.4s;
}
input:focus{
  border-color: red;
  width:200px;
}

 


6. 가상클래스 선택자 - first-child, last-child

 

-1) first child : 요소 E가 형제 요소 중 첫번째 요소라면 선택

.fruit li:first-child{
	color: red;
}
<ul class="fruits">
    <li>딸기</li> <!--선택-->
    <li>사과</li>
    <li>오렌지</li>
    <li>망고</li>
</ul>

 

-2) last-child : 요소 E가 형제 요소 중 마지막 요소라면 선택

.fruit li:last-child{
	color: red;
}
<ul class="fruits">
    <li>딸기</li> <!--선택-->
    <li>사과</li>
    <li>오렌지</li>
    <li>망고</li>
</ul>

 


7. 가상클래스 선택자 - nth-child

- nth-child :  E가 형제 요소 중 n번째 요소하면 선택 (n 키워드 사용시 0부터 시작) :  E:nth-chile(n)

.fruits li.nth-child(2n) { /*n+3*/
	color: red; 
}
<ul class="fruits">
    <li>딸기</li> 
    <li>사과</li> <!--선택-->
    <li>오렌지</li>		<!--선택-->
    <li>망고</li> <!--선택-->  <!--선택-->
</ul>

 

 

8. 가상클래스 선택자 - xxx-child 주의 사항

  • .fruits의 첫번째 자식 요소가 <p></p>가 아니기 때문에 선택되지 않는다. 
.fruits p:nth-chile(1){
	color:red;
}
<!--선택된 요소 없음-->
<div class="fruits">
    <div> 딸기</div>
    <p>사과</p> 
    <p>망고</p> 
    <span>오렌지</span>
</ul>
  • :nth-child 앞에 아무것도 안쓰고 사용 할 수 있다. 또한 >를 사용해서 바로 아래 자식 요소만 선택가능
<div class="box-group">
  <div>1</div>
  <div>2</div>
  <div>3
    <p>3-1</p>
    <div>3-2</div>
    <div>3-3</div>
  </div>
</div>
.box-group :first-child {
  color: red;
  font-weight: bold;
}

 

 

9. 가상클래스 선택자 - bth-of-type, not

-1) bth-of-type : E의 타입(태그이름)과 동일한 타입인 형제 요소 중 E가 n번째 요소라면 선택 (n 키워드 사용시 0부터 해석) : E:nth-of-type

<div class="fruits">
  <div>딸기</div>
  <p>사과</p>
  <p>망고</p>
  <span>오렌지</span>
</div>
.fruits {
  font-size: 40px;
}
.fruits p:nth-of-type(1){
  color:red;
}

 

  • nth-of-type은 태그이름을 중요시 한다. 따라서 클래스 이름으로 nth-of-type을 하면 적용되지 않는다.
<ul class="fruits">
  <li>오렌지</li>
  <li class="red">딸기</li>
  <li>망고</li>
  <li class="red">사과</li>  
</ul>
.fruits {
  font-size: 40px;
}
/* 색이 변하지 않음 */
.fruits .red:nth-of-type(1){
  color:red;
}

 

-2) not : S가 아닌 E선택 : E:not(S)

<ul class="fruits">
  <li>오렌지</li>
  <li class="strawberry">딸기</li>
  <li>망고</li>
  <li>사과</li>  
</ul>
.fruits {
  font- size: 40px;
}
.fruits li:not(.strawberry){
  color:red;
}

 


10. 가상요소 선택자 - before

- E요소 내부의 앞에, 내용을 삽입 : E::before

<!-- Emmet 문법 : ul>li{$}*10-->
<ul>
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
  <li>5</li>
  <li>6</li>
  <li>7</li>
  <li>8</li>
  <li>9</li>
  <li>10</li>
</ul>

content가 중요, content가 있어야지 적용가능

ul{
  font-size: 40px;
}
ul li::before {
  content: "숫자";
  font-weight: bold;
  color: red;
  margin-right: 20px;
}

 

 

11.  가상요소 선택자 - after

- E요소 내부의 뒤애, 내용을 삽입 : E::after

<!--Emmet 문법 : ul>li{$}*10-->
<ul>
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
  <li>5</li>
  <li>6</li>
  <li>7</li>
  <li>8</li>
  <li>9</li>
  <li>10</li>
</ul>
ul{
  font-size: 400px;
}
ul li::after{
  content: url("https://heropy.blog/css/images/logo.png");
}

 


12. 속성 선택자 - [attr], [attr=value]

-1) attr : 속성 attr을 포함한 요소 선택 : [attr]

<input type="text" value="hellozo0">
<input type="password" value="1234">
<input  type="text" value="disabled text" disabled>
[disabled] {
  opacity:0.2;
}

 

-2) attr=value : 속성 attr을 포함하며 속성 값이 value인 요소 선택

<input type="text" value="hellozo0">
<input type="password" value="1234">
<input  type="text" value="disabled text" disabled>
[type="password"] {
  opacity: 0.5;
  color:red;
}

 

 

13. 속성 선택자 - [attr^=value], [attr$=value]

-1) attr^=value : 속성 attr을 포함하여 속성 값이 value로 시작하는 요소 선택 : [attr^=value]

<button class="btn-success">Success</button>
<button class="btn-danger">Danger</button>
<button>Normal</button>
[class^="btn-"] {
  font-weight: bold;
  border-radius: 20px;
}

 

-2) attr$=value : 속성 attr을 포함하며 속성 값이 value로 끝나는 요소 선택 : [attr$=value]

<button class="btn-success">Success</button>
<button class="btn-danger">Danger</button>
<button>Normal</button>
[class$="danger"] {
  color: red;
}
[class$="success"] {
  color: green;
}

 


14. 상속(Inherit)

- 상속되는 속성들 : font(size, weight, style, height, family), color, text-align, text-indent, text-decoration, letter-spacing, opacity etc...

 

- 생태계(.ecosystem)에 적용된 색상이, 하위요소들에게 상속

.ecosystem {
  color : red;
}
<div class="ecosystem">생태계
  <div class="animal">동물
    <div class="tiger">호랑이</div>
    <div class="lion">사자</div>
    <div class="elephant">코끼리</div>
  </div>
  <div class="plant">식물</div>
</div>
.ecosystem {
	color:red;
}

 

강제상속

: 상속되지 않는 속성도 inherit이라는 값을 사용하여 부모에서 자식으로 강제 상속시킬 수 있다. 자식을 제외한 후손에게는 적용되지 않으며, 모든 속성이 강제 상속을 사용할 수 있는 것은 아니다.

<div class="parent">
	<div class="child"></div>
</div>
.parent{
  position: absolute;  /*상속되지 않는 속성과 값*/
}
.child {
  position: inherit; /*강제 상속 받아 position: absolute;와 동일*/
}

 


15. 우선순위

<body>
  <div id="color_yellow" class="color_green" style="color: orange;">Hello World!</div>
</body>
div { color: red; !important} /*!important*/
#color_yellow { color: yellow; } /*아이디 선택자*/
.color_green { color: green; } /*클래스 선택자*/

div { color: blue; } /*태그 선택자*/
* { color: darkblue; } /*전체 선택자*/
body { color: violet; } /*상속*/

- 우선순위 결정 : 같은 요소가 여러 선언의 대상이 될 경우, 어떤 속성의 CSS속성을 우선 적용할지 결정하는 방법

  1. 명시도 점수가 높은 선언이 우선(명시도)
  2. 점수가 같은 경우, 가장 마지막에 해석(늦게 작성한)되는 선언이 우선(선언 순서)
  3. 명시도는 '상속'규칙보다 우선(중요도)
  4. !importnt가 적용된 선언방식이 다른 모든 방식보다 우선(중요도)

-1) 가장중요(!important) : 모든 선언을 무시하고 가장 우선, 무한대p

div {
  color:red !important; 
}

-2) 인라인 선언방식 : 인라인 선언(HTML style속성을 사용), 1000p

<div style="color: orange;">Hello World</div>

-3) 아이디 : 아이디 선택자, 100p

-4) 클래스 : 클래스 선택자, 10p

-5) 태그: 태그 선택자, 1p

-6) 전체: 전체 선택자, 0p

-7) 상속 : 상속 받은 속성은 항상 우선하지 않음, 점수 계산X

 

- 계산예제

.list li.item { color: red;}  /*21p*/
.list li:hover { colore: red;}  /*21p*/
.box::before {content="Good "; color: red;}  /*11p*/
#submit span { color:red;}  /*101p*/

header .menu li:nth-child(2) { color:red;}  /*22p*/
h1 { color:red;}  /*1p*/
:not(.box) {color: red;}  /* 10p*/
:not(span) {color: red;}  /* 1p*/

  - :hover, :nth-child처럼 가상클래스(:)는 선택자의 점수(10p), ::before처럼 가상요소(::)는 태그선택자의 점수(1p), 부정선택자 :not()은 점수를 가지지 않는다.

'Front-end > Web' 카테고리의 다른 글

CSS - 박스모델  (0) 2021.02.02
CSS - 단위  (0) 2021.02.02
CSS - 실습환경  (0) 2021.02.02
HTML - 전역 속성, 기타  (0) 2021.02.02
HTML - 표 콘텐츠 & 양식  (0) 2021.02.02

댓글