본문 바로가기
풀스택 개발 학습 과정/프론트엔드

[HTML + CSS] CSS 1 - CSS 선택자 종류

by 육츠 2024. 2. 17.

css 를 배우기 전 우리가 글 형식을 꾸미던 방식은 태그 안에서 style 이라는 옵션을 사용하여 형식을 꾸미는 것이었다.

 <span style="color: rgb(104, 28, 176);">일부 글자만 스타일을 적용하고자 할때 사용</span>

 

하지만 해당 방식은 css의 우선순위를 가져가 디자인이 제대로 이용되지 않는다는 단점이 존재하였다.

<title> 태그 아래에 <style> 태그를 이용하여 넣는 것이 가장 바람직하다.

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>링크를 표기하는 태그</title>
    <style>
        a { text-decoration: none; }
        a:link { color: rgb(235, 112, 71); }
        a:hover { color: rgb(4, 255, 0); font-weight: bold;}
        a:active {color: yellow; font-weight: bold;}
        a:visited {color: cornflowerblue;}
    </style>
</head>

 


http://meyerweb.com/eric/tools/css/reset/  v2.0 | 20110126 License: none (public domain)
: CSS 의 형식을 모두 초기화하는 css 이다. 모두가 사용할 수 있도록 공개해 놓았다.

html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed, 
figure, figcaption, footer, header, hgroup, 
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
	margin: 0;
	padding: 0;
	border: 0;
	font-size: 100%;
	font: inherit;
	vertical-align: baseline;
}
/* HTML5 display-role reset for older browsers */
article, aside, details, figcaption, figure, 
footer, header, hgroup, menu, nav, section {
	display: block;
}
body {
	line-height: 1;
}
ol, ul {
	list-style: none;
}
blockquote, q {
	quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
	content: '';
	content: none;
}
table {
	border-collapse: collapse;
	border-spacing: 0;
}

 

파일을 따로 만들어서 CSS 이용하는 방법

<!DOCTYPE html>
<html lang="ko">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>회원 가입</title>
    <link rel="stylesheet" href="./css/reset.css"> <!--외부에서 가져오겠다 -->
    <link rel="stylesheet" href="./css/formExam.css">
</head>

 

formExam.css

.header{
    text-align: center;
    padding: 80px 0;
    /* 글자를 가운데로 */
}

.header>h1>a>img {
    height: 40px;
}

.content {
    width: 1000px;
    margin: 0 auto;
    /* 좌우 간격 자동 조정*/
    padding: 40px 20px;
    /* 안쪽 여백 */ 
    background-color: #cccccc;
}

.content ul>li{
    margin: 20px 0;
}

/*
선택자 중요 *
*/
.content ul>li>span.gender,
.content ul>li>label {
    display: inline-block;
    /* 인라인(다음 데이터와 나란히) 과 블록을 서로 변경한다*/
    width: 170px;
}

.content ul>li>select,
.content ul>li>input,
.content ul>li input:not(.check) {
    margin: 10px 0;
    padding: 10px 0;
    width: 200px;
}

.content .buttonWrap>input{
    display: block;
    background-color: #06a950;
    color: white;
    border: inherit;
    width: 300px;
    height: 40px;
    border-radius: 10px;
    font-size: 20px;
    font-weight: bolder;
    margin: 20px auto;
}

.footer {
    padding: 50px 0;
    text-align: center;
}

.footer li{
    margin: 10px;
}

.footer li span {
    line-height: 20px;
}

 

CSS 선택자

요소에 서식이나 배경을 적용하려는 요소를 정확히 선택할 수 있어야 한다.  
선택자는 이러한 요소들을 다양한 방식으로 선택할 있도록 해준다.

단순선택자

선택자 종류 내용
전체 선택자(*) 전체 요소를 선택할 사용 (특잇값 : 0)
태그명 선택자 태그 이름으로 선택할 사용 (특잇값 : 1)
그룹 선택자 콤마(,) 이용해서 동일한 스타일 정의를 가진 모든 HTML 요소를 선택할 사용
클래스 선택자 class라는 속성으로 지정한 값을 가진 모든 요소들을 선택할때 사용 (클래스는 같은 값을 여러 요소에 사용가능하므로 복수 선택 가능) (특잇값 :10)
아이디 선택자 id라는 속성으로 지정한 값을 가진 모든 요소들을 선택할때 사용(아이디는 같은 값을 하나의 요소에만 사용가능하므로 단일요소 선택 가능) (특잇값 :100)

 

사용 예

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>단순 선택자의 사용 예</title>
    <style>
        /* (cascading) 계단처럼 요소를 적용(지정)한다. */
        
        * {
            font-family: 'Times New Roman', Times, serif;
            color: darkcyan;
        }

        /* 특잇값이 11 */ 
        p.test {
            background-color:aquamarine;
        }

        /*특잇값이 10*/
        .one {
            background-color: gainsboro;
        }

        /*특잇값이 100*/
        #two {
            font-size: 1.5em; /* n배 키우는 */
        }


        #two, .three {
            color: white;
            background-color:darkred;
        }
        

    </style>
</head>
<body>
    <h2>단순 선택자의 사용 예</h2>
    <h3>종류 : 전체 선택자, 태그 선택자, 그룹 선택자, 클래스 선택자, 아이디 선택자</h3>
    
    <p class="one">
        Lorem ipsum dolor sit amet consectetur adipisicing elit. 
        Beatae, est velit sed quos tempora vero fugit placeat eligendi? 
        Ad debitis quos quae ipsa facere hic numquam fugiat accusamus officiis atque.
    </p>

    <p class="three">
        Lorem, ipsum dolor sit amet consectetur adipisicing elit. 
        Sint repellat qui accusamus esse officia libero tempore dolorum ab recusandae quisquam error, 
        similique nostrum voluptatibus et facere unde inventore. Cum, tempora.
    </p>

    <p class="one test">
        Lorem, ipsum dolor sit amet consectetur adipisicing elit. 
        Eos est ut tempore, magnam voluptate dolor quis nobis odio possimus facilis, 
        molestiae optio numquam dignissimos recusandae vitae sed officia, nemo laudantium.
    </p>

    <p id="two">
        Lorem ipsum dolor sit amet, consectetur adipisicing elit. 
        Ullam quidem eum nisi fuga quasi dolore ducimus numquam delectus necessitatibus eligendi 
        explicabo obcaecati, tenetur, in pariatur distinctio quod aperiam, natus quas.
    </p>

</body>
</html>
특잇값 = 11 특잇값 = 10
p.test {
     background-color:aquamarine;
}
.one {
     background-color: gainsboro;
}
p 태그가 없으면 우선순위(특잇값)가 동일해진다. 동일한 css 를 입히면 아래 쪽이 우선이다.  
p 태그가 존재 하게 되면 특이도가 더 높아지게 된다. 그렇다면 특이도가 높은 것이 우선순위다. (구체적이고 확실하기 때문이다)

 

가상(Pseudo) 클래스 선택자

가상 클래스는 태그나 다른 선택자 뒤에 콜론(:) 붙여 선택기능을 추가하는 키워드로
선택한 요소가 특별한 상태여야 만족하는 클래스이다.
주로 a 태그의 상태를 나눠서 가상클래스를 적용했으나, 다른 태그에도 사용할 있다.

선택자 뒤에 콜론(:) 붙여 특별한 상태에 따라 동작하도록 한다. ( :link, :hover, :active, :visited 등 )

예제 1 

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>가상 클래스 선택자</title>
    <style>
        a { text-decoration: none; }
        a:link { color: darkolivegreen;}
        a:hover, p.one:hover {
            background-color: thistle;
            font-size: 1.2em;
        }
        a:active {
            color: crimson;
        }
        a:visited {
            color: darkblue;
        }

    </style>

 

예제 2

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>테이블 콘텐츠에 CSS 적용하기</title>
    <style>
        table {
            border: 2px solid #898989;
            border-collapse: collapse;
        }
        table thead {
            background-color: crimson;
        }
        table th,
        table td {
            border: 1px solid #245 ;
            padding: 10px; 
        }

        /* = table tbody>tr:hover 
        띄어쓰기는 후손
        > 는 자식 */
        tbody tr:hover {
            background-color: coral;
            color: white;
            font-size: 1.2em;
        }
        
    </style>

[ 참고 ] w3schools 가상클래스 : https://www.w3schools.com/css/css_pseudo_classes.asp

 

CSS Pseudo-classes

W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.

www.w3schools.com

 

가상(Pseudo) 요소 선택자

가상요소는 태그의 지정된 부분에 스타일을 적용할 때 사용한다.
가상요소는 콜론 2개(::) 을 붙여 요소의 일부분에 스타일을 적용할 수 있다.
예를 들어 요소의 글자, 요소의 , 콘텐츠 앞이나 뒤에 다른 콘텐츠 삽입

 

사용 예

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>가상 요소 선택자 사용 예</title>
    <style>
        p.one::first-letter {
            color: #ff0000;
            font-size: x-large;
        }

        p.two::first-line {
            color: #00ff00;
        }

        /* 드래그로 문장을 선택해야 보인다. */
        p::selection {
            color: pink;
            background-color: azure;
        }

        p.three::before{
            content: "하하하!! ";
        }

        p.four::after {
            /* content: url(../imges/rocket.png); content 로는 이미지를 축소할 수 없다. */
            content: url(../imges/bullet.png)
        }

    </style>
</head>

[ 참고 ] w3schools 가상요소 : https://www.w3schools.com/css/css_pseudo_elements.asp

 

CSS Pseudo-elements

W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.

www.w3schools.com

 

속성 선택자

특정 속성이나 속성값을 가진 html 요소를 선택할때 사용
종류 : [속성] , [속성 = ], [속성 ~= ], [속성 ^= ], [속성 $= ], [속성 |= ], [속성 *= ]

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>속성 선택자의 사용 예</title>
    <style>
        input[type="text"] {
            width: 100px;
            transition: width .35s ease-in-out; 
            /* 폭이 자연스럽게 늘어나게 하고 0.35 초 안에 늘어나기*/
        }
        
        input[type="text"]:focus {
            width: 250px;
        }

        input[type="text"]:focus,
        input[type="password"]:focus,
        input[type="checkbox"]:focus {
            outline: 1px solid red;
            background-color: antiquewhite;
        }
        


    </style>
</head>
<body>
    <h2>속성 선택자의 사용 예</h2>

        <body>
        <h1>The width Property</h1>
        
        <p>Set the width of the input field to 100 pixels. However, when the input field gets focus, make it 250 pixels wide:</p>       
        Search: <input type="text" name="search">
        
        <p> 
            연습문제 : 
            인풋 상자를 3개정도 생성한 후 마우스로 포커스를 넣으면 인풋상자의 테두리와 배경색이 바뀌도록 하시오. 
        </p>
        <input type="text" placeholder="아이디를 입력"> <br>
        <input type="password" placeholder="비밀번호 입력"> <br>
        <input type="checkbox"> 체크하시오 <br>

</body>
</html>

 

[ 참고 ] w3schools 속성 선택자 : https://www.w3schools.com/cssref/sel_attribute.php

 

CSS [attribute] Selector

W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.

www.w3schools.com

 

종속 선택자

이상의 선택자를 조합해서 사용하는

종류 내용
공백 하위항목 선택 
&gt; (자식선택자) 인접한 하위 항목을 선택
+ (형제 선택자) 같은 상위 클래스를 가진 연다른 다음 요소
~ (일반 형제선택자) 같은 상위 클래스를 가진 요소들
<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>종속 선택자의 사용 예</title>
    <style>
        #container>ul {
            border: 1px dotted blue;
        }

        h3+ul {
            color: violet;
            font-weight: bold;
        }

        h3~ul{
            color: blue;
            font-weight: bold;
        }
    </style>
</head>
<body>
    <h2>종속 선택자의 사용 예</h2>
    <section id = "container">
        <header>
            <h3>예약 방법 및 요금</h3>
        </header>

        <p>요안도라에 예약하려면? </p>
        
        <ul>
            <li>예약방법
                <ul>
                    <li>직접 통화</li>
                    <li>문자 남기기</li>
                </ul>
            </li>
            <li>요금
                <ul>
                    <li>1인 : 40,000원</li>
                    <li>2인 : 60,000원</li>
                    <li>3인 : 80,000원</li>
                    <li>4인 : 100,00원</li>
                </ul>
            </li>
        </ul>
    </section>
</body>
</html>

 

기타 : not(선택자) - 괄호 안에 작성