웹개발 교육/CSS

[5일] CSS (2) - 선택자 활용, 포지셔닝

ewok 2022. 8. 1. 17:55

태그의 상세 속성 접근

        <div id="nav">
        ...
                    <p class="news">세계</p>
            <ol>
                <li>손흥민</li>
                <li>김연아</li>
                <li>박지성</li>
                <li><a href="https://www.itwill.co.kr/">아이티윌</a></li>
            </ol>
        </div>

<li> 태그 중 어느 한 개만 접근하는 것도 가능하다.

/* 태그의 상세 속성 접근 */
#nav > ol >li:nth-child(2) { /*<li> 요소 중에서 2번째 */
    font-weight: bold;
}

/* 아이티윌 링크만 CSS 적용 */
#nav > ol > li > a {
    width: 200px;
    height: 100px;
    background-color: hotpink;
    text-decoration-style: wavy;
}

#nav > ol >li:nth-child(2) 여기에서는 순서를 1부터 매겨서 2. 김연아에 css가 적용되었다. 보통 0부터 시작하지만 1부터 시작하는 경우도 있다.

 

Active Selector

a:link     - 일반적 링크 및 방문하지 않은 링크
a:visited  - 방문했던 링크
a:hover    - 마우스 올렸을 때 링크
a:active   - 마우스 누르는 순간의 링크
a:link {color: black; text-decoration: none;}
a:visited {color: black; text-decoration: none;}
a:hover {color: black; text-decoration: none;}
a:active {color: black; text-decoration: none;}
<a href="http://www.naver.com">네이버</a>

 

Reset CSS

우리의 css를 적용하기 전 css의 기본 속성을 전부 제거하기도 한다.

브라우저들은 기본적인 스타일을 가지고 있다. 그런데 이 브라우저들 마다 각각 다른 스타일을 가지고 있기 때문에

같은 css를 적용해도 Edge, Chrome, Firefox 등의 브라우저에서 사용자에게 비추어지는 모습이 모두 다를 수 있다.

이러한 문제를 해결하기 위해서 브라우저의 스타일을 모두 초기화해서 동일하게 만든 뒤 스타일을 추가해나가 모든 브라우저에서 같은 화면을 볼 수 있게 해주는 것이다.

 

reset.css를 검색하면 아래 사이트가 나온다.

https://meyerweb.com/eric/tools/css/reset/

 

CSS Tools: Reset CSS

CSS Tools: Reset CSS The goal of a reset stylesheet is to reduce browser inconsistencies in things like default line heights, margins and font sizes of headings, and so on. The general reasoning behind this was discussed in a May 2007 post, if you're inter

meyerweb.com

여기서 코드를 가져와 css의 기본 속성들을 제거한 뒤 우리의 css를 입힐 수 있다.

<!DOCTYPE html>
<html lang="ko">
    <head>
        <title>06_reset.html</title>
        <link rel="stylesheet" href="reset.css">
    </head>  
    <body>
        <h1>대한민국</h1>
        <strong>무궁화</strong>
        <p>오필승 코리아</p>

        <ul>
            <li>국어</li>
            <li>영어</li>
        </ul>

        <ol>
            <li>개나리</li>
            <li>진달래</li>
        </ol>
    </body>
</html>

css reset 결과

이제 지난 시간에 만든 css 파일을 import 시켜보자

...
        <link rel="stylesheet" href="mystyle05.css">
...

 

포지셔닝(레이아웃)

  • 브라우저 화면 안에 박스 형태의 각 콘텐츠를 원하는 위치에 배치하는 것이다.
  • 수평, 수직, 그리드 방향으로 배치할 수 있다.
  • position : 'static | relative | fixed | absolute | sticky'

 

참고

https://www.w3schools.com/css/css_positioning.asp

 

CSS Layout - The position Property

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

 

static

position:static;

<div style="position:static;">

가장 기본이다. 수직으로만 배치되며 문서의 흐름에 맞추어 배치된다.

포지션 예

 

Absolute

position:absolute;

 #s1 li:nth-child(1) {
                background-color: red; position: absolute; left: 100px; top: 30px;
            }

absolute는 자신의 자리가 없어진다.

            #s1 li:nth-child(1) {
                background-color: red;  position: absolute; right: 0px; bottom: 0px;
            }

 

section에 위치를 주지 않았기 때문에 body를 기준으로 위치를 잡게 된다.

 

Relative

position:relative

부모 영역을 기준을 한다.

            /* 부모 ul, 자식 li */
            #s1 ul {background: yellow; height: 300px; position: relative;}
            #s1 li:nth-child(1) {background-color: red;
                                 position: absolute;
                                 --left: 0;
                                 --top: 0;
                                 right: 0;
                                 bottom: 0;}
            #s1 li:nth-child(2) {background-color: green;}
            #s1 li:nth-child(3) {background-color: blue;}

 

노란색 영역의 <ul> 태그 밖으로 나간 absolute와는 다르게 <ul>안에 국어가 온다. (기준점이 <body>냐 <ul>이냐의 차이)

 

relative는 absolute와 달리 요소의 자기 위치가 살아있다.

<!DOCTYPE html>
<html lang="ko">
    <head>
        <title>10_relative.html</title>
        <link rel="stylesheet" href="reset.css">
        <style>
            #s1 ul {background: yellow; height: 300px; width: 300px; position: relative;}
            #s1 li:nth-child(1) {background-color: red; position: relative; left: 50px; top: 30px;}
            #s1 li:nth-child(2) {background-color: green;}
            #s1 li:nth-child(3) {background-color: blue;}
        </style>
    </head>  
    <body>

        <!-- 상대적 위치 position:relative -->
        <section id="s1">
            <h3>position:relative</h3>
            <ul>
                <li>손흥민</li>
                <li>박지성</li>
                <li>김연아</li>
            </ul>
        </section>

    </body>
</html>

박지성 위의 공간이 남아 있는 것을 확인할 수 있다.

absolute

absolute는 영어 위 공간이 남아 있지 않는 것을 볼 수 있다.

 

fixed

<!DOCTYPE html>
<html lang="ko">
    <head>
        <title>11_fixed.html</title>
        <link rel="stylesheet" href="reset.css">
        <style>
            #s1 ul {background-color: yellow;}
            #s1 li:nth-child(1) {background: red;}
            #s1 li:nth-child(2) {background: green;
                                 --position: absolute;
                                 --position: relative;
                                 position: fixed;
                                 left: 100px;
                                 top: 100px;}
            #s1 li:nth-child(3) {background: blue;}
        </style>
    </head>
        <body>

        <!-- 고정 위치 position: fixed -->
        <section id="s1">
            <h3>position:fixed</h3>
            <ul>
                <li>개나리</li>
                <li>진달래</li>
                <li>라일락</li>
            </ul>
        </section>
        <!-- 문서의 길이를 강제로 길게. 수직 스크롤이 나올 수 있게 해서 테스트 -->
        <p>KOREA</p>
        ...
        </body>
</html>

top
bottom

위치가 고정되어 있다.

 

화면 하단에 고정

             /* 2) 화면 하단에 고정 */
            #s1 ul {background-color: yellow;}
            #s1 li:nth-child(1) {background: red;}
            #s1 li:nth-child(2) {background: green;
                                 position: fixed;
                                 bottom: 0px;
                                 height: 80px;
                                 width: 100%;
                                }
            #s1 li:nth-child(3) {background: blue;}

 

부모의 포지션을 지정해도 하단에 고정되어 있는 모습을 볼 수 있다.

브라우저 화면을 기준으로 보기 때문에 어떠한 부모에게도 종속되지 않는다.
            /* 3) 부모 포지션 지정 */
            #s1 ul {background-color: yellow; position: relative; height: 300px;}
            #s1 li:nth-child(1) {background: red;}
            #s1 li:nth-child(2) {background: green;
                                 position: fixed;
                                 bottom: 0px;
                                 height: 80px;
                                 width: 100%;
                                }
            #s1 li:nth-child(3) {background: blue;}

 

Sticky

top:0을 주지 않으면 상단에 고정이 되지 않는다.

w3school 설명

 

#header {height: 70px;
         background-color: aqua;
         position: sticky;
         width: 100%;
         top: 0; /* sticky 줄 때 필수 사항 */
        }

 

float

화면 레이아웃 기법

  • position속성 : 배치 방법을 지정
  • float속성    : 레이어를 왼쪽 또는 오른쪽 위치 지정. 수평을 기준으로 정렬하기 (요소가 부모요소 기준으로 왼쪽 또는 오른쪽에 배치할 때 지정)
  • clear속성    : float속성을 해제
  • z-index속성  : 레이어 순서를 정함  

 

변경 전

<!DOCTYPE html>
<html lang="ko">
    <head>
        <title>13_float.html</title>
        <style>
            div {border: 1px solid blue; width: 100px; height: 100px;}
        </style>
    </head>  
    <body>
        <!-- float : 레이어 배치하기 -->
        <div>BOX 1</div>
        <div>BOX 2</div>
        <div>BOX 3</div>
    </body>
</html>

변경 후

1.

/* 2) div 블럭요소의 세로 배치를 가로 배치로 변경 */
div {border: 1px solid blue; width: 100px; height: 100px; float: left;}

 

2.

.box4 {float: right;}
...
<div class="box4">BOX4</div>

 

참고

https://www.w3schools.com/css/css_float.asp

 

CSS Layout - float and clear

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

 

layout

위 그림과 같이 레이아웃을 설정하려고 한다.

 

전체 레이아웃 구성하기

    <body>
        <div class="container">
            <header>Header</header>
            <div class="inner">
                <section>Section 1</section>
                <section>Section 2</section>
                <section>Section 3</section>
            </div>
            <footer>Footer</footer>
        </div>
    </body>
</html>
  • 빨간색 테두리 : .container
  • 연두색 테두리 : <header>, .inner, <footer>
  • 파란색 테두리 : section 1, 2, 3
<style>
    /* 1) */
    .container {
        border: 2px solid blue;
        width: 900px;
        margin: auto;
    }
    /* 2) */
    header {
        border: 2px solid red;
        height: 150px;
        width: 100%;
        line-height: 150px;
        text-align: center;
    }
    /* 3) */
    .inner section {
        border: 2px solid green;
        width: 300px;
        height: 300px;
        float: left;
    }
</style>

section이 3개 전부 가로로 되지 않는 이유는 container 크기는 900px을 주었는데 section의 크기는 300+4(border의 크기)px이기 때문이다. section이 container의 크기를 넘어가 한 줄에 나타나지 않는다.

따라서 한줄에 표시하기 위해서는 container의 크기를 912px로 해야한다.

/* 4) 각 .inner section 스타일에서 2+300+2 (왼쪽선 굵기 + 가로 크기 + 오른쪽선 굵기) * 3개 */
.container {
    border: 2px solid blue;
    width: 912px;
    margin: auto;
}

하지만 이 과정을 수행하는 속성이 있다.

바로 box-sizing이다.

.inner section {
    border: 2px solid green;
    width: 300px;
    height: 300px;
    float: left;
    box-sizing: border-box; /* 선 굵기, 여백 등으로 늘어난 부분은 container의 width=900px 내에서 해결함 */ 
}

 

/* float 속성은 전 요소 속성을 상속받는 특징이 있음. 이미 float:left가 있는 상태이다 */
/* 8) */
footer {border: 5px solid orange; height: 100px;}

그래서 다음과 같이 나온다.

이를 해결하기 위해 상속받은 float:left를 지워야 하는데, 이를 지우는 속성이 있다.

clear이다. (clear 값으로는 left, right, both가 있다.)

/* 9) clear : float 속성 해제 6)에서 상속받은 float:left 속성을 지워야 한다 */
footer {border: 5px solid orange; height: 100px; clear: left;}

/* 10) 완성코드 */
footer {border: 5px solid orange; height: 100px; clear: both; /* left, right 모두 해제 */}

 

z-index

여러 개의 레이아웃이 있을 때 먼저 보여지는 순서를 정한다.

<style>
    #aa {background-color: red; width: 100px; height: 100px; position: absolute; left: 0; top: 0; z-index: 3;}
    #bb {background-color: green; width: 80px; height: 200px; position: absolute; left: 0; top: 0; z-index: 5;}
    #cc {background-color: blue; width: 60px; height: 300px; position: absolute; left: 0; top: 0; z-index: 1;}

특별히 정해진 숫자는 없다. 음수도 허용되며 임의로 부여하면 된다. 숫자가 클수록 가장 앞에 온다.

여기서는 z-index 값이 5로 가장 큰 녹색이 맨 앞에 위치하고

그 다음 빨강, 파랑 순이다.

참조

https://www.w3schools.com/css/css_z-index.asp

 

CSS Layout - The z-index Property

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

 

부모자식요소

자식요소(absolute)는 부모요소(relative)를 기준으로 위치한다. 

<!DOCTYPE html>
<html lang="ko">
    <head>
        <title>16_부모자식요소.html</title>
        <style>
            body {margin: 0;}

            .parent {
                width: 600px;
                height: 300px;
                background-color: gold;
                margin: 150px;
                position: relative;
            }

            .child {
                width: 100px;
                height: 50px;
                background-color: gray;
                right: 0;
                bottom: 0;
                position: absolute;
            }
        </style>
    </head>  
    <body> <!-- style="position: relative" 속성이 이미 있는 상태이다-->

        부모요소 : relative / 자식요소 : absolute
        <hr>

        <div class="parent">
            <div class="child"></div>
        </div>
    </body>
</html>

노란색 : 부모 / 회색 : 자식