1. box-sizing

: box model 을 사용할 때 지정하는 속성 중 하나로, 기존 box model 사용 시의 불편함을 없애려고 만들었다.

 

기존의 문제점

holy grail layout 등을 만들면서 box model을 사용하여 padding, border, width 등을 지정할 때, html 태그의 width가 여러 float 속성을 적용한 요소들의 width의 합과 맞아떨어져야 보기좋은 레이아웃이 만들어지는데, 이때 각 요소들의 border과 margin 값을 고려하여(추가로 더해서) width 값을 예상해야 하는 불편함이 있었다.

ex) element1의 width는 300, border는 10, element2의 width는 400, border는 15, margin은 20일 경우

-> html태그의 width는 300 + 10*2 + 400 + 15*2 + 20*2 = 790으로 지정해야 오차가 없다.

 

특히 다음의 세 가지 경우에 width 값을 계산하기 복잡했다.

 

경우1) 두 element의 border 값이 다를 경우

<html>
  <head>
    <style>
        #red{border:10px solid red ; padding:10px ; margin:10px ; width:150px ; box-sizing:content-box}
        #blue{border:30px solid blue ; padding:10px ; margin:10px ; width:150px ; box-sizing:content-box}
    </style>
  </head>
  <body>
        <div id="red">Ryan</div>
        <div id="blue">Ryan</div>
  </body>
</html>

경우2) 두 element의 padding 값이 다를 경우

#red{border:10px solid red ; padding:10px ; margin:10px ; width:150px ; box-sizing:content-box}
#blue{border:10px solid blue ; padding:30px ; margin:10px ; width:150px ; box-sizing:content-box}

경우3) 두 element의 margin 값이 다를 경우

#red{border:10px solid red ; padding:10px ; margin:10px ; width:150px ; box-sizing:content-box}
#blue{border:10px solid blue ; padding:10px ; margin:30px ; width:150px ; box-sizing:content-box}

=> 이 경우마다 width를 직접 margin, padding, border 값을 고려해서 계산해야 했으므로 이 문제를 해결하기 위해서 box-sizing 속성이 추가되었다.

 

그러면 box-sizing 속성은 정확히 무엇인가?

위의 문제는 width 속성이 'border를 포함하지 않은 컨텐츠만의 너비'를 기준으로 했기 때문에 발생했다.

위 사진에서처럼, width의 기본값 속성은 정확히 말하면 border 안의 content(하얀 부분) 이므로, 빨간 선처럼 문서의 시작점에서부터 500px의 거리를 재면 당연히 이 상자는 너비를 초과한다.

그러나 box-sizing 속성에서 다른 값을 기준으로 하면, 어떤 값의 경우 문서의 시작점부터 border 끝까지의 너비를 width의 기준으로 삼을 수도 있다.

이처럼 box-sizing 무엇을 기준으로 width 속성을 결정할 것인지를 직접 지정할 수 있게 해 준다.

* 다만 width가 꼭 content의 순수 너비는 아니다. 위처럼 다른 속성값(value)을 사용한다면, 가령 '시작점부터 box 끝의 "거리"' 처럼, "거리"의 의미로 사용될 수도 있다.

 

이 속성은 2가지 값을 가진다:

1) box-sizing:content-box

: 기본값. width를 border, margin, padding을 일절 포함하지 않은 content만의 너비라고 지정.

-border를 설정하면 상자의 너비가 달라짐.

-width가 content 영역의 너비라는 의미로 사용됨.

 

2) box-sizing:border-box

: width를 border를 포함한 element의 너비라고 지정.

-border를 설정해도 상자의 너비가 달라지지 않음. 대신에 안의 content 영역이 줄어듬.

-width가 시작점부터 border의 끝까지의 거리라는 의미로 사용됨.

 

2. flex

: 레이아웃을 쉽게 잡기 위해 사용하는, 레이아웃을 위해서 고안된 도구.

cf) position, float 속성을 이용해도 레이아웃을 구현할 수 있지만, flex는 레이아웃을 제 1 목적으로 만든 도구이다.

 

특징

: 항상 같이 다니는 부모-자식 관계의 element가 있다.

<container>
	<item>
    </item>
</container>

부모 <container> 과 자식 <item>은 항상 같이 다닌다.

그리고 각 태그에는 서로 다른 속성을 부여할 수 있다.

* 이때 둘은 부모-자식 '태그' 가 아니라 '요소들(elements)'이다.

실제로 구현하려면 id나 class의 이름을 저렇게 정의하거나, 혹은 이름도 다르게 지정해도 된다. 중요한 것은 부모-자식 관계의 태그가 있어야 flex를 사용할 수 있다는 것이다.

 

적용하기

적용하려면 바깥(부모) 태그의 display 속성값이 flex로 되어있어야 한다.

<html>
<head>
   <meta charset="utf-8">
    <style>
        .container{
            display:flex ; <!-- 이 속성이 있어야 flex 사용가능 -->
            width : 200px ; height:200px ; background-color:lightblue
        }
        .item{
            background-color:lightpink ; border:1px solid white ; text-align:center
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="item">A</div>
        <div class="item">B</div>
        <div class="item">C</div>
        <div class="item">D</div>
        <div class="item">E</div>
        <div class="item">F</div>
        <div class="item">G</div>
    </div>
</body>
</html>

우선은 flex 속성 중, 부모 태그에 적용되는 속성을 먼저 알아보자.

1. flex-direction 속성

여기서 display:flex 속성 아래에 바로 direction, 즉 방향을 설정할 수 있다.

이 속성은 부모 태그에 지정한다!

**단, display 속성값이 flex가 아니라면 적용되지 않는다.

flex-direction 속성의 경우 4가지 값을 가질 수 있다. 각 값에 따라 글자가 써지는 방향이 달라진다!

: row , row-reverse , column , column-reverse. 

1) row : 기본값. 왼쪽부터 글자가 써짐.

 .container{
            display:flex ; 
            flex-direction: row ;
            width : 200px ; height:200px ; background-color:lightblue
        }

 

2) row-reverse : 오른쪽부터 글자가 써짐. 글자가 써지는 방향이 반대 방향!

* text-align : right 이랑은 다름. 얘는 아예 글자의 순서도 반대가 되어버림.

flex-direction : row-reverse

3) column : 위쪽부터 글자가 써짐.

flex-direction : column

4) column-reverse : 아래쪽부터 글자가 써짐.

flex-direction : column-reverse

다음은 flex 속성 중, 자식 태그에 사용되는 속성을 알아볼 것이다.

 

1. flex-basis 속성

: 개별적 자식 태그에 적용 가능함. flex : display 속성이 이미 적용된 상태에서, 몇몇의 자식 태그 요소에게만 너비/길이값을 부여해주는 속성이다.

만약 flex-direction 속성이 적용되어 있다면, 값이 row 이면 너비, column이면 높이 값으로 적용된다.

        .item{   <!-- 개별 item 요소의 너비(row이므로)를 40px으로 증가 -->
            background-color:lightpink ; border:1px solid white ; text-align:center;
            flex-basis:40px

이렇게 자식 태그 전체에 적용할 수도 있고, 

        .item:nth-child(2){
            flex-basis:200px
        }

이렇게 하나의 개별 요소에만 적용할 수도 있다.

* 이때, nth-child(N)에서, flex-direction 방향의 순서에 따라 N번째 요소에 적용된다.

ex)

        .container{
            display:flex ; 
            flex-direction : row-reverse;  <!-- flex-direction 방향 다르다면? -->
            height:300px ; background-color:lightblue
        }
        .item{
            background-color:lightpink ; border:1px solid white ; text-align:center;
        }
        .item:nth-child(2){
            flex-basis:200px
        }

flex-direction 방향이 row-reverse인 경우, 맨 오른쪽부터 1번째, 2번째, ... 이렇게 순서가 매겨진다.

이때 .item : nth-child(2) 라면, 오른쪽으로 세었을 때를 기준으로 2번째 요소에 해당 속성이 적용되는 것이다.

 

2. flex-grow 속성

: 위의 경우는 컨텐츠의 너비/높이값이 화면 전체(여기서는 부모 태그의 영역)를 채우기 부족해서 여백이 항상 남았다.

만약 너비/높이에서의 여백을 없애고 컨텐츠 영역으로 고르게 채우고 싶을 때 이 속성을 사용한다.

* display : flex 인 상태에서만 사용가능!

* flex-grow 속성은 양수 값을 가질 수 있다.

 

경우1) 전체 자식태그에서 flex-grow : 0 => 기본값

경우2) 전체 자식태그에서 flex-grow : 1 => 전체 너비/높이를 모든 자식태그 요소가 골고루 나눠 가짐

        .item{
            background-color:lightpink ; border:1px solid white ; text-align:center;
            flex-grow:1
        }

여백이 사라지고 컨텐츠가 남은 여백을 골고루 받았다.

경우3) 일부 자식태그에서 flex-grow : 1, 나머지는 0 => 일부 자식태그가 전체 너비/높이를 나눠 가짐

        .item:nth-child(2n+3){
            flex-grow:1
        }

3, 5, 7 번째 요소만 너비를 나눠 가졌다.

경우4) flex-grow 의 값이 2 이상이라면?

ex) A의 flex-grow : a , B의 flex-grow : b 인 경우,

나머지 요소들은 원래 컨텐츠 너비만큼만 차지.

A는 나머지 여백의 a/(a+b) 만큼, B는 b/(a+b) 만큼만 차지.

* 3개 이상의 요소들이어도 마찬가지! ex) a/(a+b+c)

        .item:nth-child(3){
            flex-grow:1
        }
        .item:nth-child(4){
            flex-grow:3
        }

전체 여백이 4라면, C와 D가 1:3의 비율로 여백을 가져간다.

3. flex-shrink 속성

전제조건이 있다.

더보기

1) display : flex 인 상태

2) 해당 자식태그 요소의 flex-basis 값이 설정된 상태

에서 창 너비/높이가 줄어들어서 원래 요소들의 크기보다 작아질 때, 어떤 요소의 너비/높이를 줄일지를 결정함

경우1) 기본값 : 모든 요소가 flex-shrink : 0 인 경우

=> 어떤 요소도 창이 줄어들 때 너비/높이가 줄어들지 않는다.

경우2) 하나의 요소가 flex-shrink : 1인 경우

=> 창이 작아지면 해당 요소의 너비/높이만 이에 비례해서 줄어든다.

        .item:nth-child(1){
            flex-basis:600px ; flex-shrink:1
        }    

기본 상태(창 너비가 충분)
창 너비가 줄어든 상태. A의 영역만 아까보다 줄어들고 나머지 영역의 너비는 그대로 남아있음.

경우3) 몇 개의 flex-shrink 값이 2 이상인 경우

flex-grow 와 비슷. 서로 파이를 나눠 먹는 것과 같다.

=> A의 flex-shrink : a , B의 flex-shrink : b 인 경우, A는 줄어든 면적의 a/(a+b) , B는 b/(a+b) 만큼 줄어든다.

        .item:nth-child(1){
            flex-basis:300px ; flex-shrink:1
        }
        .item:nth-child(2){
            flex-basis:300px ; flex-shrink:4
        }

기본 상태. A와 B의 너비가 같음.
창 너비가 줄어든 상태. A보다 B의 너비가 더 많이 줄어들었다.

 

3. flex 속성으로 holy grail layout 구현하기

아까 언급한 flex-direction , flex-basis , flex-grow , flex-shrink 속성을 이용하면 float 과 position을 사용하는 것보다 더 쉽게 레이아웃을 구현할 수 있었다.

더보기

layout 구현 시 중요하게 사용했던 속성

1) flex-direction

: 세로로 배치될 header, segment(메인 컨텐츠), footer 부분은 flex-direction : column으로 설정,

segment(메인 컨텐츠) 안에서 가로로 배치될 nav, main, aside 부분은 flex-direction : row 로 설정.

2) flex-shrink (* 그 전에 flex-basis 값을 지정해야 함)

: 창 크기가 부족할 때, 메인 컨텐츠는 계속 나타나게 하고 싶다면

=> nav와 aside만 flex-shrink : 1 로 설정.

<html>
<head>
   <meta charset="utf-8">
    <style>
        .container{
            display:flex ; 
            flex-direction:column ;
            text-align:center ;
        }
        .content{
            display:flex ;
        }
        header{border-bottom: 1px solid black ; padding-left:20px}
        footer{border-top : 1px solid black ; padding:20px}
        .content nav{border-right : 1px solid black}
        .content aside{border-left : 1px solid black}
        nav,aside{flex-basis : 400px ; flex-shrink:1}
    </style>
</head>
<body>
    <div class="container">
       <header>
           <h1>WELCOME</h1>
       </header>
        <div class="content"><nav><ul>
            <li>Corporis</li> <li>fugit</li> <li>maxime</li> <li>ut</li> <li>veniam</li> <li>quo</li> <li>dolorum</li> <li>repellendus</li> <li>ab</li> <li>soluta</li> <li>voluptates</li> <li>velit</li></ul>
        </nav>
        <segment>
            <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Id cum autem pariatur debitis quae delectus eum temporibus animi quis ad, rerum doloremque non distinctio, minus enim, nihil. Dolores officiis, iusto commodi. Harum, accusamus quas pariatur autem odio sequi tempore obcaecati ab commodi, optio assumenda, unde et tenetur quisquam beatae doloribus. Porro hic odio molestias doloremque, vitae laborum voluptatibus quam deleniti placeat. Explicabo consequatur sit nemo animi reiciendis amet ratione quod possimus fuga eos ab, minima aspernatur voluptatum iure aperiam, dolorum, porro totam saepe. </p><p>Aut beatae, deleniti fugit commodi quis distinctio doloribus culpa est recusandae, illum magni itaque magnam a corrupti nam id, dolorum sapiente iste quidem non, velit error reiciendis. Laborum sint veniam sunt in impedit temporibus architecto deleniti dicta tempore, repudiandae dolor facilis aliquid ea distinctio. Assumenda magnam ratione laudantium eligendi molestias quo, natus voluptatum quos ullam rerum unde vel debitis consequuntur porro, ipsam repellat aliquid saepe maxime impedit asperiores fugiat cupiditate dolores beatae. Sequi quas a culpa magnam voluptates quibusdam, consequatur odit inventore fuga suscipit molestiae sed rem quaerat voluptatem velit, mollitia nemo, animi adipisci.</p> <p>Sapiente dignissimos enim reiciendis, iure? Doloribus nostrum officiis placeat temporibus mollitia assumenda quis tempore accusantium eius vitae laboriosam saepe deserunt nihil accusamus impedit, omnis nobis ab cupiditate iste repellendus facilis inventore! In quisquam maxime molestias itaque nam nobis eligendi, rem ullam autem alias quos deleniti, culpa quas dolores illum animi labore repellendus ab! </p>
        </segment>
        <aside>
             Nisi mollitia praesentium id cumque est repellat hic, animi, qui natus assumenda nihil repudiandae asperiores neque laudantium soluta.
        </aside></div>
        <footer>
            GOODBYE
        </footer>
    </div>
</body>
</html>

따로 width, border 등을 계산하지 않고도 선과 배치가 맞아떨어지는 layout을 구현할 수 있다.

 

 

 

 

'front-side > CSS' 카테고리의 다른 글

8. 그래픽  (0) 2021.04.12
7. 레이아웃  (0) 2021.04.07
5. brackets ~ 레이아웃 기초 내용  (0) 2021.04.02
4. 타이포그래피-font ~ 조화  (0) 2021.04.01
3. 선택자 fin ~ 타이포그래피  (0) 2021.03.30

1. <brackets> 프로그램

: Editor의 일종으로, Atom보다 편리한 기능들이 들어있는 HTML, CSS, Javascript 등에 사용할 수 있는 에디터이다.

=> 앞으로는 이 에디터를 쓸 것 같다.

여기에 Emmet 추가 프로그램을 설치하면 대략 5가지 이상의 기능을 편리하게 쓸 수 있다.

더보기

1) 태그 자동완성 by [Tab]

ex) html 입력하고 Tab 누르면:

<html></html> 자동 완성

2) 여러 개의 태그 자동완성 by (태그 이름)*(반복할 수) + [Tab]

ex) li*3 입력하고 Tab 누르면:

<li></li>

<li></li>

<li></li> 자동 완성

3) 여러 개의 태그 포함관계 완성 by (상위 태그)>(하위 태그)

ex) html > head > style 입력하고 Tab 누르면:

<html>

 <head>

  <style>

  </style>

 </head>

</html>  자동 완성

+ 2번과 3번 합치기도 가능

4) 다음 태그로 넘어가기 가능 by [Ctrl]+[Alt]+[→]

5) 미리보기 기능 : 번개 모양 아이콘 클릭

 

2. 레이아웃

2-1. 인라인 VS 블럭레벨

: 태그의 종류이다.

더보기

인라인(inline) : 해당 태그를 사용해도 한 줄에 여러 태그와 요소 사용 가능

블럭레벨(block-level) : 해당 태그를 사용하면 한 줄에 한 태그만 사용 가능

<html>
<head>
    <style>
        h1,a{border:1px solid deepskyblue}
    </style>
</head>
<body>
    <h1>Hello User</h1>   
    Welcome to  <a href="https://google.com" target="_blank">Search</a> Engine!
</body>
</html>

위처럼 <h1> 태그는 따로 줄바꿈을 하지 않았는데도 한 줄을 혼자 사용하고, <a> 태그의 테두리는 다른 태그들의 영역과 한 줄에 같이 표시된다. 이 차이가 인라인과 블럭레벨의 차이이다.

 

위처럼 기본값이 인라인인 태그가 있고 블럭레벨인 태그가 있다.... 그러나 이를 바꿀 수 있다!

=> <style> 태그 문법에서 display 속성을 이용하면 가능하다.

<html>
<head>
    <style>
        h1{border:1px solid indianred ; display:inline}
        a{border:1px solid indianred ; display:block}
    </style>
</head>
<body>
    <h1>Hello User</h1>   
    Welcome to  <a href="https://google.com" target="_blank">Search</a> Engine!
</body>
</html>

이번에는 a 태그가 한 줄을 전부 사용하고, h1 태그는 다른 요소/태그들과 한 줄을 공유하고 있다. 

 

2-2. Box Model

인라인과 블럭레벨과도 연관되어 있다. 각 요소들 사이의 간격과 관련이 있다. 

더보기

1. box model에는 크게 디섯 가지 요소가 있다.

1) border : 테두리. margin과 padding 사이의 간격을 의미

<html>
<head>
   <meta charset="utf-8">
    <style>
        #aa{display:block ; border : 10px solid forestgreen ;}
        #bb{display:block ; border : 20px solid gold ;}
    </style>
</head>
<body>
    <h1>Hello User</h1>   
    Welcome to  <a href="https://google.com" target="_blank">Search</a> Engine!
    <p id="aa">Υπάρχουν πολλές εκδοχές των αποσπασμάτων του Lorem Ipsum διαθέσιμες, αλλά η πλειοψηφία τους έχει δεχθεί κάποιας μορφής αλλοιώσεις, με ενσωματωμένους αστεεισμούς, ή τυχαίες λέξεις που <a href="https://google.co.kr">δεν</a> γίνονται καν πιστευτές.</p>   
    <p id="bb">Εάν πρόκειται να χρησιμοποιήσετε ένα κομμάτι του Lorem Ipsum, πρέπει να είστε βέβαιοι πως δεν βρίσκεται κάτι προσβλητικό κρυμμένο μέσα στο κείμενο. Όλες οι γεννήτριες Lorem Ipsum στο διαδίκτυο τείνουν να επαναλαμβάνουν <a href="https://google.co.kr">προκαθορισμένα</a> κομμάτια του Lorem Ipsum κατά απαίτηση, καθιστώνας την παρούσα γεννήτρια την πρώτη πραγματική γεννήτρια στο διαδίκτυο.</p>
</body>
</html>

2) margin : 주로 화면의 양 끝과 block element의 사이 간격을 의미

<html>
<head>
   <meta charset="utf-8">
    <style>
        #aa{display:block ; border : 10px solid forestgreen ;
        margin : 50px}
        #bb{display:block ; border : 10px solid gold ;
        margin : 100px}
    </style>
</head>
<body>
    <h1>Hello User</h1>   
    Welcome to  <a href="https://google.com" target="_blank">Search</a> Engine!
    <p id="aa">Υπάρχουν πολλές εκδοχές των αποσπασμάτων του Lorem Ipsum διαθέσιμες, αλλά η πλειοψηφία τους έχει δεχθεί κάποιας μορφής αλλοιώσεις, με ενσωματωμένους αστεεισμούς, ή τυχαίες λέξεις που <a href="https://google.co.kr">δεν</a> γίνονται καν πιστευτές.</p>   
    <p id="bb">Εάν πρόκειται να χρησιμοποιήσετε ένα κομμάτι του Lorem Ipsum, πρέπει να είστε βέβαιοι πως δεν βρίσκεται κάτι προσβλητικό κρυμμένο μέσα στο κείμενο. Όλες οι γεννήτριες Lorem Ipsum στο διαδίκτυο τείνουν να επαναλαμβάνουν <a href="https://google.co.kr">προκαθορισμένα</a> κομμάτια του Lorem Ipsum κατά απαίτηση, καθιστώνας την παρούσα γεννήτρια την πρώτη πραγματική γεννήτρια στο διαδίκτυο.</p>
</body>
</html>

3) padding : border 테두리와 그 안의 텍스트의 간격을 의미

<html>
<head>
   <meta charset="utf-8">
    <style>
        #aa{display:block ; border : 10px solid forestgreen ;
        padding : 50px}
        #bb{display:block ; border : 10px solid gold ;
        padding : 100px}
    </style>
</head>
<body>
    <h1>Hello User</h1>   
    Welcome to  <a href="https://google.com" target="_blank">Search</a> Engine!
    <p id="aa">Υπάρχουν πολλές εκδοχές των αποσπασμάτων του Lorem Ipsum διαθέσιμες, αλλά η πλειοψηφία τους έχει δεχθεί κάποιας μορφής αλλοιώσεις, με ενσωματωμένους αστεεισμούς, ή τυχαίες λέξεις που <a href="https://google.co.kr">δεν</a> γίνονται καν πιστευτές.</p>  
    <p id="bb">Εάν πρόκειται να χρησιμοποιήσετε ένα κομμάτι του Lorem Ipsum, πρέπει να είστε βέβαιοι πως δεν βρίσκεται κάτι προσβλητικό κρυμμένο μέσα στο κείμενο. Όλες οι γεννήτριες Lorem Ipsum στο διαδίκτυο τείνουν να επαναλαμβάνουν <a href="https://google.co.kr">προκαθορισμένα</a> κομμάτια του Lorem Ipsum κατά απαίτηση, καθιστώνας την παρούσα γεννήτρια την πρώτη πραγματική γεννήτρια στο διαδίκτυο.</p>
</body>
</html>

4) width : 테두리 상자(border)의 가로폭.

<html>
<head>
   <meta charset="utf-8">
    <style>
        #aa{display:block ; border : 10px solid forestgreen ;
        width : 500px}
        #bb{display:block ; border : 10px solid gold ;
        width : 1000px}
    </style>
</head>
<body>
    <h1>Hello User</h1>   
    Welcome to  <a href="https://google.com" target="_blank">Search</a> Engine!
    <p id="aa">Υπάρχουν πολλές εκδοχές των αποσπασμάτων του Lorem Ipsum διαθέσιμες, αλλά η πλειοψηφία τους έχει δεχθεί κάποιας μορφής αλλοιώσεις, με ενσωματωμένους αστεεισμούς, ή τυχαίες λέξεις που <a href="https://google.co.kr">δεν</a> γίνονται καν πιστευτές.</p>
    <p id="bb">Εάν πρόκειται να χρησιμοποιήσετε ένα κομμάτι του Lorem Ipsum, πρέπει να είστε βέβαιοι πως δεν βρίσκεται κάτι προσβλητικό κρυμμένο μέσα στο κείμενο. Όλες οι γεννήτριες Lorem Ipsum στο διαδίκτυο τείνουν να επαναλαμβάνουν <a href="https://google.co.kr">προκαθορισμένα</a> κομμάτια του Lorem Ipsum κατά απαίτηση, καθιστώνας την παρούσα γεννήτρια την πρώτη πραγματική γεννήτρια στο διαδίκτυο.</p>
</body>
</html>

5) height : 테두리 상자(border)의 세로폭. height를 고정했는데 텍스트의 양이 많으면 삐져나올 수 있다.

<html>
<head>
   <meta charset="utf-8">
    <style>
        #aa{display:block ; border : 10px solid forestgreen ;
        height : 50px}
        #bb{display:block ; border : 10px solid gold ;
        height : 100px}
    </style>
</head>
<body>
    <h1>Hello User</h1>   
    Welcome to  <a href="https://google.com" target="_blank">Search</a> Engine!
    <p id="aa">Υπάρχουν πολλές εκδοχές των αποσπασμάτων του Lorem Ipsum διαθέσιμες, αλλά η πλειοψηφία τους έχει δεχθεί κάποιας μορφής αλλοιώσεις, με ενσωματωμένους αστεεισμούς, ή τυχαίες λέξεις που <a href="https://google.co.kr">δεν</a> γίνονται καν πιστευτές.</p> 
    <p id="bb">Εάν πρόκειται να χρησιμοποιήσετε ένα κομμάτι του Lorem Ipsum, πρέπει να είστε βέβαιοι πως δεν βρίσκεται κάτι προσβλητικό κρυμμένο μέσα στο κείμενο. Όλες οι γεννήτριες Lorem Ipsum στο διαδίκτυο τείνουν να επαναλαμβάνουν <a href="https://google.co.kr">προκαθορισμένα</a> κομμάτια του Lorem Ipsum κατά απαίτηση, καθιστώνας την παρούσα γεννήτρια την πρώτη πραγματική γεννήτρια στο διαδίκτυο.</p>
</body>
</html>

 

2. inline display 와 border display에 따라서 적용되는 방식이 다르다

1) inline display의 경우, 4), 5)번인 width 와 height 속성이 적용되지 않는다.

2) margin의 기준이 '화면의 양 끝과 element의 사이' 가 아니라 '양 element의 간격'이다.

<html>
<head>
    <style>
        #aa{display:block ; border : 10px solid forestgreen ;
        height : 50px ; margin : 100px ; padding : 20px  ; width : 300px}
        #bb{display:inline ; border : 10px solid gold ;
        height : 50px ; margin : 100px ; padding : 20px  ; width : 300px}
    </style>
</head>
<body>
    <h1 id="aa">Hello User</h1> 
    <a id="bb" href="https://google.com" target="_blank">rabindranath</a> tagore
</body>
</html>

2-3. Position(포지션)

: box model에서 각 컨텐츠 사이의 간격을 설정했다면, position은 각 요소를 배치할 위치를 설정한다.

position은 속성이고, 4가지 종류가 있다.

1. static

: 기본값. position이 설정되지 않은 상태. 자신이 속한 부모 태그와의 위치를 기준으로 한 상태!

2. relative

: static인 상태와 비교했을 때 얼마나 움직이는지를 설정. 부모 태그와의 기본 위치를 기준으로 얼마나 움직일지를 설정.

얼마나 움직이는지는 해당 element를 위/아래/왼쪽/오른쪽 으로 몇 px 움직일지로 설정하는데,

이때 이런 top/bottom/left/right 의 값을 offset(오프셋)이라고 한다.

(* position:relative 를 지정하지 않고 offset 값만 지정하면 반영되지 않는다.)

1) 오프셋을 지정할 때, 이동하려고 하는 방향과 반대 방향으로 지정해야 한다!

ex) 해당 요소를 왼쪽으로 이동시키려고 하면 offset을 right으로 지정

2) offset 적용 시 우선순위가 존재한다.

: top > bottom , left > right 

ex) top 과 bottom 을 모두 지정한다면 top offset 값만 반영된다. left/right도 마찬가지.

<!DOCTYPE html>
<html>
  <head>
    <style>
      ol{border:3px dashed ; bordindexolor:deepskyblue}
        ul{text-align:center ; font-size:1rem}   
      #toright{position:relative ; left:150px}
      #toleft{position:relative ; right:150px}
      #totop{position:relative ; bottom:50px}
      #tobottom{position:relative ; top:50px}  
    </style>
  </head>
  <body>
   <ul>
    	<li id="totop">HTML</li>   <!-- 위로 이동 -->
    	<li id="toleft">CSS</li>   <!-- 왼쪽으로 이동 -->
    	<li style="font-weight:bold">JavaScript</li>   <!-- 아무 포지션 서식 적용 안 함 -->
    	<li id="toright">Python</li>   <!-- 오른쪽으로 이동 -->
    	<li id="tobottom">C</li>   <!-- 아래쪽으로 이동 -->
   </ul>
  </body>
</html>

3. absolute

: relative와는 다르게, 자신의 바로 위 부모가 아니라 자신의 부모 중 position 값이 static이 아닌 부모와의 위치를 기준으로 움직인다.

-> 그러므로 바로 위 부모와의 관계가 거의 끊긴다.

(그래서 border로 경계를 표시하면, 부모와 관계가 있을 때는 부모의 width를 따라가는 반면 관계가 끊긴다면 부모의 width를 따라가지 않고 딱 자신의 영역만큼으로 border의 너비가 제한된다. 소속이 애매해지기 때문임.)

cf) 만약 자신의 부모 태그(상위 태그)의 position 값이 전부 static이라면, 해당 태그의 offset 값은 최상위 태그인 <html> 태그의 위치를 기준으로 삼게 된다.

 

ex1) 기준 태그의 position 값이 absolute , 그 태그의 모든 상위 태그의 position은 static 일 때:

<html>
<head>
    <style>
        #parent{position:static}
        div{border:2px solid ; margin:20px ; text-align:center}
        #child{position:absolute ; left:0px ; top:0px ; background-color:coral}
    </style>
</head>
<body>
    <div>Coffee
        <div id="parent">Blended
            <div>Smoothie
                <div>Mango Smoothie</div>
                <div>Strawberry Smoothie</div>
            </div>
            <div>Frappchino
                <div>Mocha Frappchino</div>
                <div id="child">Zavachip Frappchino</div>
            </div>
        </div>
    </div>
</body>
</html>

: 해당 태그(Zavachip Frappuchino)는 offset 값이 상하좌우로 0px인데, 화면 맨 상단에 위치해 있으므로 <html> 태그를 기준으로 값을 정했음을 알 수 있다.

 

ex2) 기준 태그의 position 값이 absolute, html 다음으로의 상위 태그의(body 태그 제외) position이 absolute이고 나머지는 static일 때:

<html>
<head>
   <meta charset="utf-8">
    <title>Example</title>
    <style>
        #parent{position:absolute}
        div{border:2px solid ; margin:20px ; text-align:center}
        #child{position:absolute ; left:0px ; top:0px ; background-color:coral}
    </style>
</head>
<body>
    <div>Coffee
        <div id="parent">Blended
            <div>Smoothie
                <div>Mango Smoothie</div>
                <div>Strawberry Smoothie</div>
            </div>
            <div>Frappchino
                <div>Mocha Frappuchino</div>
                <div id="child">Zavachip Frappuchino</div>
            </div>
        </div>
    </div>
</body>
</html>

: 이번엔 기준값이 화면 좌상단이 아니라, #parent 가 적용된 Blended 부모 태그로 바뀌었다.

그런데 아까는 각 태그 요소들이 화면 폭을 다 채운 데에 비해, 지금은 position:absolute 인 Blended 요소를 포함한 하위 요소들은 화면 폭을 다 채우지 못한다.

        #parent{position:relative}

parent id의 속성을 relative로 바꾸면, Zavachip의 위치는 그대로이나 나머지 요소들은 다시 화면 폭을 그대로 채운다.

=> position:relativeposition:absolute 의 차이는 단순히 자식 태그의 위치 기준이 바로 위의 부모 태그인지, position:static 이 아니면서 그나마 가장 가까운 부모 태그인지 만의 차이가 아닌 것이다. 화면상의 정렬에도 둘의 차이가 있다!

더보기

<정리>

1. relative 와 absolute 의 차이는 자식 태그의 위치가 누구를 기준으로 하는지이다.

1) relative : 바로 위의 부모 태그

2) absolute : 바로 위가 아닐 수도 있다. position:static 이 아니면서 가장 가까운 부모 태그를 기준으로 한다.

* 즉 position:absolute 또는 position:relative 인 가장 가까운 부모 태그의 위치를 기준으로 한다.

** 그러나 이 둘도 다르다. (자식 태그의 위치 기준이 최상위 html 태그가 아닐 경우에만 두 경우가 다름)

2-1) absolute : 요소들이 화면에 꽉 차게 정렬되지 않음

2-2) relative : 요소들이 화면에 꽉 차게 조절되어 정렬됨

4. fixed

: 스크롤바를 내려도 해당 element를 지정한 위치에 고정시켜 주는 '속성'이다.

absolute, relative와 마찬가지로 left, top 등으로 위치를 지정한다.

absolute와 비슷한 점 : 사용하면 바로 위 부모 태그와의 관계가 끊긴다. -> 해당 태그/element의 영역이 딱 그 안의 텍스트만 포함하는 범위로 제한된다.

<html>
<head>
    <style>
        #fix{position:fixed ; left:10px ; top:10px ; background-color:black ; color:white}
        #plus{position:fixed ; right:20px ; top:50px ; background-color:black ; color:limegreen}
    </style>
</head>
<body>
  <h1 style="text-align:center">KSY</h1>  <!-- 고정하지 않은 영역-->
   <h2 id="fix">CornSalad</h2>  <!-- 고정한 영역 1 -->
   <h4 id="plus">Most Delicious Appetizer Ever</h4>  <!-- 고정한 영역 2 -->
    <p style="margin-top:70px">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ex animi officia fugit molestias. Delectus odit, numquam reprehenderit eius adipisci illo, minus impedit voluptas excepturi aspernatur debitis labore, quasi dolore tempore. Reprehenderit voluptatibus accusantium consectetur sapiente sequi culpa eligendi totam aliquam libero, non modi nisi aperiam delectus ad sunt natus ex fuga quibusdam, debitis ratione est vel! Itaque eaque molestias fuga ab doloremque at, fugit ullam quia, debitis corporis ad, deserunt possimus distinctio qui? Perspiciatis explicabo optio aspernatur ducimus cum facere libero ab modi iure reiciendis perferendis praesentium voluptas voluptatibus, ullam, nemo veniam necessitatibus obcaecati tenetur similique consequatur voluptate.</p>
   
</body>
</html>

: 스크롤을 내리면 지정한 영역만 계속 고정되어 있다.

 

2-4. Float

1. float & clear

더보기

1) float 속성

이미지를 자연스럽게 배치하는 데 주로 사용하지만, 레이아웃에도 사용되는 '속성'.

정확히는 이미지 태그 <img>에 지정하면 해당 이미지와 영역이 겹치는 다른 element들로 하여금 해당 이미지의 영역을 비껴가게 해 준다.

-> 이미지를 왼쪽에, 해당 글은 바로 오른쪽에 배치하는 등의 연출이 가능하다.

 

float에는 2가지 값을 지정할 수 있다 : left 또는 right

left : 이미지를 왼쪽에 정렬

right : 이미지를 오른쪽에 정렬

 

2) clear 속성

 

float 속성을 무력화시킨다.

* float 속성은 img 태그(다른 element가 '피해가게 할' 대상)에 적용하지만, 

<-> clear 속성은 다른 태그('그 element를 피하는 대상') 에 적용한다. (ex. p 태그)

주로 <style> 태그 안 img 태그에는 float 속성을 일반적으로 적용하고, float 속성을 적용하고 싶지 않은 일부 단락에 clear 속성을 적용하는 것으로 보인다.

 

clear에는 3가지 값을 지정할 수 있다 : left , right , both

left : float의 값이 left인 경우에만 float 속성을 무력화

right : float의 값이 right인 경우에만 float 속성을 무력화

both : float의 값에 상관없이 float 속성을 무력화  -> 셋 중에 가장 많이 쓰임

<html>
<head>
   <meta charset="utf-8">
    <title>Example</title>
    <style>
        img{width:200px ; float:right ; margin:15px}    
    </style>
</head>
<body>
   <img src="C:\Users\USER\Desktop\WEB\image\start.jpg" alt="Start Now!" target="_blank"> 
   <!-- float만 설정, clear 는 설정 안 함-->
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Vitae culpa, necessitatibus cum repudiandae, sit architecto voluptatum! Neque nulla possimus ex perspiciatis sunt, commodi, debitis saepe error nam reiciendis ut! Commodi nisi voluptatum tempora in perspiciatis, eum deserunt ratione? Doloremque autem aliquam eligendi deserunt iusto minima provident enim.</p>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Vitae culpa, necessitatibus cum repudiandae, sit architecto voluptatum! Neque nulla possimus ex perspiciatis sunt, commodi, debitis saepe error nam reiciendis ut! Commodi nisi voluptatum tempora in perspiciatis, eum deserunt ratione? Doloremque autem aliquam eligendi deserunt iusto minima provident enim.</p>
   <img src="C:\Users\USER\Desktop\WEB\image\start.jpg" alt="Start Now!" target="_blank">
   <!-- float와 clear 모두 설정되어서 float 설정이 무력화됨-->   
    <p style="clear:both">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Vitae culpa, necessitatibus cum repudiandae, sit architecto voluptatum! Neque nulla possimus ex perspiciatis sunt, commodi, debitis saepe error nam reiciendis ut! Commodi nisi voluptatum tempora in perspiciatis, eum deserunt ratione? Doloremque autem aliquam eligendi deserunt iusto minima provident enim.</p>           
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Vitae culpa, necessitatibus cum repudiandae, sit architecto voluptatum! Neque nulla possimus ex perspiciatis sunt, commodi, debitis saepe error nam reiciendis ut! Commodi nisi voluptatum tempora in perspiciatis, eum deserunt ratione? Doloremque autem aliquam eligendi deserunt iusto minima provident enim.</p>
</body>
</html>

위 이미지는 float 설정이 적용되어서 텍스트와 같이 나타나고, 아래 이미지는 float 속성이 적용되었지만 clear 속성으로 무력화되어서 기존의 html처럼 같은 줄에 텍스트와 이미지가 나타나지 않고 있다.

 

2. holy grail layout

: '최적의 구현' 이라는 의미로, 웹사이트를 가장 잘 나타내는 구현 방식을 찾는 것은 매우 어렵다는 뜻에서 나온 말인 듯 

보통 웹사이트는 이런 식의 구현을 많이 사용하는데, 이는 기존의 HTML 태그만을 사용해서는 불가능했고, CSS에 와서야 float, clear 등의 속성을 이용하면서 가능해졌다.

더보기

<holy grail layout> 만드는 방법

1) 각 태그에게 적절한 역할 부여하기

: header, navigation bar, main content, ad, footer 등 다양한 부분으로 이루어져 있는데, 각 영역의 내용을 태그로 구분해줘야 한다.

* 단 임의로 태그를 사용하고 id나 class를 정의하는 것보다 기존에 존재했고 여러 영역/구성의 의미를 담은 html 태그를 사용하는 것이 더 바람직하다.

b/c 태그에는 그 내용이 전체 본문에서 어떤 역할을 하는지가 포함되어 있다.

cf) 바람직하지 못한 경우 : 제목을 head 태그로 표현하지 않고 strong, font-size 등으로 겉으로만 제목처럼 보이게 하기

 

그런 의미에서 각 영역의 역할을 나타내기에 적절한 html 태그들이 있다:

* 이 태그들을 그냥 html에서 사용하면 전혀 구분되지 않는다. 이 태그는 '의미상' 사용하고, 이를 시각적으로 구분짓는 것은 2단계에서 할 일이다.

-<header> : header. 페이지의 맨 위에 오는 중요한 핵심 내용을 나타내는 부분을 담당하는 태그

-<nav> : navigation bar. 왼 쪽의 목차나 다른 페이지를 안내하는 영역을 담당하는 태그

-<article> : (꼭 이 태그를 쓰는 것만은 아님) 여러 내용이 있을 때, 각각 다른 주제로 글을 구분하기 위해 사용하는 태그

-<aside> : 부수적인 내용을 나타내는 태그

-<footer> : 글의 맨 마지막, 밑 부분에 나오는 영역을 담당하는 태그

 

2) 시각적으로 각 태그의 영역을 구분하기 : float , clear 속성 이용

[주의1] 레이아웃에서 같은 줄을 공유하는 부분은 navigation bar, main content, ad 영역이고 나머지 header이랑 footer 영역은 다른 영역과 너비를 공유하지 않게 해야 한다.

-> 위 세 영역에 float 속성을 적용한다.

+) 통상적으로 내용은 위->아래, 왼쪽->오른쪽으로 작성되므로 맨 왼 쪽에 오는 영역(navigation bar) 부터 float 효과를 주고, 방향을 left로 지정한다.

[주의2] 여러 영역이 삐져나오지 않기 위해선 float와 width를 같이 지정해야 한다.

[주의3] 마지막의 footer 영역은 float효과의 영향을 받으면 안 되므로, clear:both 속성을 이용해서 float 효과를 무력화시킨다.

[주의4] float 속성 적용한 세 영역을 구분하는 border를 설정하는데, 어떤 영역이 더 긴지에 상관없이 해당 border가 header과 footer 영역 사이를 모두 이을 수 있게 해야 한다.

[주의5] 창 사이즈를 조절하다가 간격이 좁아지면 float 속성이 깨지고 레이아웃이 흐트러진다.

-> 본문 전체의 너비를 고정시키는 방법을 사용할 수 있다.

* 창의 사이즈에 따라서 레이아웃의 크기가 자동 조절되는 것도 바람직하지만, 아직은 구현할 수 없다.

* 이때 border의 두께 값이 전체 테두리에 포함되지 않는다. 이를 고려해야 한다.

(페이지 우클릭 -> 검사 에서 각 영역의 width, border width를 확인할 수 있지만 너무 번거롭다.

=> box-sizing 방법은 border width를 각 영역의 width를 더할 때 같이 포함시키는 방법을 알려준다.)

ex) 한 영역의 너비가 300px, border가 50px이면 총 너비는 350px이므로 주의해야 한다.

* flex : 창의 넓이 등 다양한 변화 상황에서 레이아웃을 좀 더 쉽게 짤 수 있도록 도와준다. [심화과정]

* margin:auto 로 설정하면 해당 element를 가운데 정렬시키는 것과 같은 효과를 낼 수 있다!

 

<실습>

<html>
<head>
   <meta charset="utf-8">
    <title>Holy Grail Layout</title>
    <style>
        h1{text-align:center ; background-color:black ; color:white}
        .fix{width:700px ; border:1px solid black ; margin:auto}
        header{border-bottom:1px solid black ; text-align:center}
        nav{float:left ; border-right:1px solid black ; margin-right:0px ; width:150px ; padding:10px}
        article{float:left ; border-left:1px solid black ; border-right:1px solid black ; width:350px ; margin-left:-1px ; margin-right: 0px ; padding:20px }
        aside{float:left ; border-left:1px solid black ; width:100px ; padding:10px ; margin-left:0px}
        footer{clear:both ; border-top:1px solid black ; padding:20px ; text-align:center}
    </style>
</head>
<body>
<div class="fix">
<header><h1>Italian Food</h1><p>Qui eos a aut cum obcaecati sint sit, laborum. Autem, in neque.</p></header>
<nav><ul>
    <li>Pasta</li>
    <li>Pizza</li>
    <li>Risotto</li>
    <li>Salad</li>
    <li>Steak</li>
</ul></nav>
    <article><p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aliquid numquam iusto fugit quia ea ipsum sint earum alias tempore quibusdam, voluptatibus suscipit nisi, saepe et adipisci amet. Deleniti vitae nisi, ullam quod voluptatum doloremque facilis corrupti omnis, consequuntur blanditiis cupiditate itaque voluptatem minima odit quo soluta id sapiente! Voluptate dolore fuga autem sit omnis, consequatur quia pariatur qui non tenetur eum expedita provident a nisi repellat iste, sequi accusamus maiores molestias et labore ratione illo, minus perspiciatis. Architecto nemo itaque facilis nam excepturi reiciendis nostrum ducimus sunt rerum. Doloremque quidem veniam rem delectus, facere aliquam nam nemo quisquam? Laborum eos qui voluptatem, culpa amet officia in dicta, quibusdam numquam modi at repellendus fugiat est consequuntur porro illum dignissimos maiores deleniti? Deserunt assumenda dolorem provident fugiat, natus, modi facere itaque amet ipsum, omnis dolore, animi quis sed atque consectetur magni.</p><p> Accusantium ab numquam adipisci doloremque necessitatibus fugit minima, illum totam odit veniam ducimus voluptatem sunt tempora, culpa voluptates commodi vitae consequuntur ipsum dicta! Pariatur, voluptates, velit. Deserunt tenetur eum autem suscipit harum sequi reprehenderit totam officiis, quis corporis nam, exercitationem ut fugiat aperiam consequatur dicta eaque omnis qui quas, aut porro dolores a. Quos necessitatibus eius illum nesciunt et, fugit itaque est provident sunt eligendi non animi corporis officiis atque modi dolores nulla nemo, numquam excepturi, consectetur.</p><p> Asperiores, nihil excepturi. Nesciunt tenetur eaque voluptatem deleniti aperiam quisquam accusantium, maxime placeat voluptates velit expedita, cumque, obcaecati, quae repellendus. Et nulla, in cum nisi itaque ea, doloremque magnam deleniti dolore doloribus asperiores nobis ipsa aliquam corporis vero, rerum, hic accusamus.</p><p> Laborum provident cupiditate harum perferendis voluptate fuga laudantium animi et tenetur veniam, vitae maxime distinctio doloribus quisquam delectus unde tempora, sunt nam recusandae a saepe inventore. Minima, saepe. Culpa repellat qui totam similique earum aspernatur molestiae debitis atque aperiam vitae in excepturi expedita veniam adipisci, velit voluptatibus exercitationem asperiores nostrum quod distinctio. Alias, consectetur sed optio voluptatum recusandae, aliquid repellat deserunt consequuntur delectus vero, exercitationem facere quidem. Perspiciatis reprehenderit omnis sit ducimus voluptates, quasi recusandae a, eligendi, maiores labore ipsam natus laborum vero at dicta. Ipsa velit dolor quis asperiores illum obcaecati repudiandae dicta magni, adipisci fugit voluptate eaque, quos, assumenda aut. Nisi quas velit nihil voluptate culpa qui architecto, voluptatibus, esse minima corporis dicta pariatur eius. Amet corporis necessitatibus quia, inventore neque!</p><p> Voluptatem rem id architecto sed animi libero asperiores officia reprehenderit! Quae accusamus illo beatae et dignissimos dolore sed optio eligendi amet. Aliquam architecto ipsam facilis, exercitationem laboriosam dolor mollitia suscipit. Fugit quo, eum possimus. Corporis officiis, rerum facere sequi dolore sed iste, mollitia praesentium repellendus ratione est tenetur. Molestiae iure beatae, delectus quasi, ipsum at! Quasi eius minus ex, minima rem voluptates velit, non deleniti voluptas error, modi possimus qui iusto numquam vero, sed maiores! Nostrum, illo magnam iusto architecto id esse voluptatum repellat! Impedit fugiat quidem esse itaque. Hic inventore voluptatem id dolorem esse, voluptas perferendis, facilis autem voluptates nesciunt commodi ab dignissimos accusantium qui ex sequi tempora numquam, consequatur et nulla itaque non neque eius deserunt? Eveniet, necessitatibus.</p></article>
<aside> Nisi perferendis pariatur provident, blanditiis aliquam aspernatur expedita earum sit eos rerum voluptates vero, soluta laborum necessitatibus beatae non sequi nobis recusandae.</aside>
<footer>Molestias nisi vitae officia id, explicabo praesentium!</footer>
    </div>
</body>
</html>

 

 

'front-side > CSS' 카테고리의 다른 글

7. 레이아웃  (0) 2021.04.07
6. 레이아웃 추가(심화)내용  (0) 2021.04.05
4. 타이포그래피-font ~ 조화  (0) 2021.04.01
3. 선택자 fin ~ 타이포그래피  (0) 2021.03.30
2. 선택자  (0) 2021.03.29

#1. 타이포그래피-font

: font-family 등을 사용해서 글꼴 조정 가능

1. font-family : 글꼴 적용

1) 글씨체로 글꼴 적용

=> font-family : (글꼴이름)

2) 해당 글꼴이 적용 안 될 때는 여러 개로 순차적 적용 가능

=> font-family : (글꼴1) , (글꼴2) , (글꼴3)

+ 두 단어 이상일 경우에는 ""로 묶기

ex) font-family : Nanumgothic , "Times New Roman"

3) 포괄적 글꼴 적용 가능

: serif , sans-serif , cursive , fantasy , monospace 적용 가능. 이들은 특정 글꼴 이름이 아니라, 앞에서 언급한 글꼴이 컴퓨터에 없을 경우 적용될 수 있는, 어느 컴퓨터에나 있는 포괄적인 글꼴임.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>TYPOGRAPHY</title>
    <style>
      h3{text-align : center}
      #type11{font-family : sans-serif ; color: indianred}
      #type12{font-family : serif ; color: indianred}
      #type13{font-family : cursive ; color: indianred}
      #type14{font-family : fantasy ; color: indianred}
      #type15{font-family : monospace ; color: indianred}
    </style>
  </head>
  <body>
    <h3 id="type11">Dark Chocolate and Wafer</h3>
    <h3 id="type12">Dark Chocolate and Wafer</h3>
    <h3 id="type13">Dark Chocolate and Wafer</h3>
    <h3 id="type14">Dark Chocolate and Wafer</h3>
    <h3 id="type15">Dark Chocolate and Wafer</h3>
  </body>
</html>

2. font-weight : 글꼴 굵게 서식 적용

: font-weight : bold  로 설정하면 같은 글꼴인데 굵게만 표시된다.

ex) <h3 font-weight:bold>Dark Chocolate</h3>

3. line-height : 줄간격 서식 적용

: line-height : (숫자)  로 설정하면 해당 태그/id/class 선택자의 줄간격을 설정할 수 있다.

이때 두 가지 방법으로 설정 가능

1) 줄간격의 배수 = 그냥 숫자만 입력

ex) <h2 line-height:2>Hello World</h2>

(기본 줄간격은 1.2 이다)

2) pixel로 지정 = (픽셀 값) px  입력

ex) <h2 line-height:200px>Hello World</h2>

- px는 줄간격의 배수와 달리, 화면 확대나 브라우저 설정을 변경해서 글씨 크기가 바뀌어도 줄간격이 이에 따라 바뀌지 않아서 추천하지 않음

 

#2. 타이포그래피 - 웹폰트

: 사용자가 갖고 있지 않은 폰트를 다운로드받아서 사용할 수 있는 방법

*폰트의 용량이 너무 크다면 주의해야 한다.

1. 구글의 폰트 사용

: fonts.google.com 에서 폰트 다운로드

2-1) <link> 태그 안의 href url을 포함한 코드를 복사해서 붙여넣기

ex) <link rel="preconnect" href="https://fonts.gstatic.com">

 <link href="~~~~~" rel="stylesheet">  이런 형태의 코드를 <head> 태그 안에 붙여넣는다.

: <link> 태그 안의 href 속성을 이용하면, html 실행 시 href 안의 링크를 불러온다고 한다.

2-2) <style> 태그 안의 font-family 를 포함한 코드를 복사해서 붙여넣기

ex) <style>#아이디이름{font-family:폰트이름}</style>

: 그러나 이 경우는 font-family에 이미 구글 폰트의 글꼴이 있어야만 간단하게 코드 한 줄로 작성할 수 있고, 아니라면 아래의 더 복잡한 2번 방법을 사용해야 한다.

2. 개인이 갖고 있던 폰트를 웹폰트로 바꿔서 사용

-> (생각보다 더 어려워서 따라 실행하진 못했다ㅠㅠ)

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <link rel="preconnect" href="https://fonts.gstatic.com">
<link href="https://fonts.googleapis.com/css2?family=Train+One&display=swap" rel="stylesheet">
    <style>
      h3{text-align : center}
      #type41{font-family: 'Train One', cursive;}
    </style>
  </head>
  <body>
    <h3 id="type41">Dark Chocolate and Wafer</h3>
    <h3>Dark Chocolate and Wafer</h3>
  </body>
</html>

 

#2. 조화

CSS 수업에서 하나의 element는 여러 디자인 서식의 영향을 받을 수 있다. 만약 여러 서식이 중첩으로 적용된다면 어떤 규칙에 의해 하나의 서식이 우선적으로 적용되는데, <조화> 부분에서는 어떤 규칙이 적용되는지를 알아볼 것이다.

#2-1. 상속

상속(Inheritance) : 부모 요소가 가진 속성들을 자식 요소가 물려받는 개념

상속이 있는 이유는 코드 작성의 편리함 때문이다.

ex) 문서 전체에 서식을 적용하고 싶다면, 개별 요소에 서식을 적용하는 것보다 <body>나 <html> 태그 하나에 속성을 적용시키면, 이 태그는 모든 태그들의 부모 태그이므로 코드 한 줄로 본문 전체에 서식이 적용된다.

 

※ 그러나 모든 속성이 상속되는 것은 아니다.

b/c 상속되어야 유리한 속성이 있고, 상속되지 않아야 유리한 속성이 있기 때문이다.

ex) color 속성은 상속됨 <-> border 속성은 상속되지 않음!

* 어떤 속성이 상속되는지는 www.w3.org/TR/CSS21/propidx.html 여기서 확인할 수 있다.

 

+) 주석 처리 정리

1) 한 줄 단위로 주석 다는 방법

: <!--  comment -->

2) 여러 줄 단위로 주석 다는 방법

: /*

(   comment

    comment     )

*/

#2-2. stylish

: 그동안 배운 CSS를 웹페이지 생산의 관점이 아닌, 소비의 관점에서 보는 방법들 중 하나

= 내가 자주 사용하는 웹사이트의 디자인 서식을 직접 바꿀 수 있는 방법이다.

 

*방법*

더보기

1. 구글 검색창에 stylish + (브라우저 이름) 검색   

ex. stylish chrome 검색

2. 검색하면 맨 상단에 나오는 Stylish 사이트에 들어가서 프로그램 설치.

3. chrome의 경우 우측 상단의 stylish 아이콘 선택 후, 'find more styles' 영역 클릭하면 사이트로 이동.

4. userstyles.org/styles/browse/google 이 웹사이트에는 google, stackoverflow, netflix 등 다양한 웹사이트에 해당하는 디자인 서식들이 있는데, 두 가지 선택지가 있다:

4-1. 다른 사람들이 올려놓은 서식을 그대로 다운로드 받을 수 있다.

=> 구글 사이트에서 슈퍼마리오 스타일을 다운받았다!

4-2. 내가 직접 웹사이트를 선택하고 서식을 변경할 수 있다.

나는 생활코딩 웹사이트에 서식을 적용하려고 했는데, 강의의 설명을 그대로 따라했지만 서식이 적용되지 않았다; 'Style' 바가 안 나와서 !important 명령을 적용할 수 없었던 듯 하다.

(디자인 서식 뒤에 !important  를 붙이면 해당 서식을 경쟁 관계의 서식보다 우선적으로 적용하도록 한다)

 

#2-3. cascading

웹사이트는 웹 브라우저, 사용자, 저자의 디자인이 자유롭게 결합될 수 있는 공간이다.

하지만 여러 디자인이 적용되는 경우, 우선순위를 고려하는 규칙이 적용된다.

 

규칙1.

웹 브라우저 < 사용자 < 저자

: 웹페이지 저자가 지정한 디자인은 사용자와 웹 브라우저가 바꿀 수 없다.

또한 요즘은 사용자가 웹 디자인을 변경할 수 있는 권한을 주지 않는 웹사이트들도 많아서, 사용자가 디자인에 관여하는 면이 점차 줄어들고 있다.

 

규칙2.

tag selector < class selector < id selector < style attribute

: 가장 구체적이고 세부적인 속성이 먼저 적용된다!

id 는 하나의 대상에만 적용되고, class 는 여러 대상에 적용 가능하므로, id가 더 세부적이라고 판단된다.

<!DOCTYPE html>
<html>
  <head>
    <style>
      li {color:tomato ; text-align:center ; font-size:1.5rem} <!-- tag selector -->
      #ids {color:pink}  <!--id selector -->
      .classes {color:purple}  <!- class selector -->
    </style>
  </head>
  <body>
      <li id="ids" class="classes" style="color:blue">html</li>    <!-- style attribute-->
  </body>
</html>

 

 

 

 

 

'front-side > CSS' 카테고리의 다른 글

6. 레이아웃 추가(심화)내용  (0) 2021.04.05
5. brackets ~ 레이아웃 기초 내용  (0) 2021.04.02
3. 선택자 fin ~ 타이포그래피  (0) 2021.03.30
2. 선택자  (0) 2021.03.29
CSS Tutorial:  (1) 2021.03.24

#1. 가상 클래스 선택자(pseudo class selector)

: class 선택자처럼 여러 대상에 속성을 지정할 수 있지만, class 선택자는 아닌 것을 의미

=> id나 class 또는 태그 지정:pseudo class selector {디자인 속성 지정}

ex) #fancy:hover{background-color:blue}

: id가 fancy인 요소에 마우스가 올려져 있을 때(=hover)->가상클래스선택자 해당 서식을 적용한다는 의미

 

가상 클래스 선택자에도 여러 종류가 있는데, 그 중 간단하게 몇 가지만 알아보았다.

1) active

: 해당 요소를 클릭하고 있을 때를 의미.

2) visited

: 주로 <a> 태그와 함께 사용. 이미 클릭한 링크에 적용됨

3) link

: visited 와 반대 경우에 사용. 클릭하지 않은 <a> 링크에 적용됨

4) hover

: 해당 부분에 마우스 커서를 올리고 있을 때 디자인 서식이 적용됨

 

+) 그 외, 지난 시간에 배운 부분도 pseudo class selector로 사용될 수 있음

ex) p i:first-child   => <p> 태그 안의 <i> 태그 중 first-child 인 요소에만 디자인 적용

 

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>beta file</title>
    <style>
      #one:hover {background-color:IndianRed}
      #two:hover{background-color:lightSalmon}
      #three:hover{background-color:gold}
      #four:hover{background-color:greenyellow}
      #five:hover{background-color:lightskyblue }
      
      a.stylish:visited{color:green}
      strong.stylish:hover{background-color:lavender}
      a.ping:active{background-color:lightsteelblue ; color:black}
    </style>
  </head>
  <body>
      <p>his article is about the mathematical study of optimizing agents. For the mathematical study of sequential games, see <strong class="stylish">Combinatorial game theory</strong>. For the study of playing games for entertainment, see Game studies. For the YouTube series, see <strong>MatPat</strong>. For other uses, see <strong class="stylish">Game theory</strong> (disambiguation).</p>
      <a href="naver.com"Complex systems organizational map.jpg></a>
      <a href="daum.com"Complex systems></a>
    <ol>
    <li id="one">  Topics </li>
    <li id="two">  Self-organization </li>
    <li id="three">  Collective behaviour </li>
    <li id="four">  Networks </li>
    <li id="five">  Evolution and adaptation </li>
    <li class="stylish">  Pattern formation </li>
    <li class="stylish">  Systems theory </li>
    <li class="stylish">  Nonlinear dynamics </li>
    <li class="stylish">  Game theory </li>
  </ol>

    <h3>Reference Sites</h3><ul>
    <li><a href="https://opentutorials.org/course/1" class="stylish">  Part of a series on </li></a>
    <li><a href="https://youtube.com" class="stylish">  Economics </li></a>
    <li><a href="https://naver.com" class="ping">  IndexOutlineCategory </li></a>
    <li><a href="https://daum.net" class="ping">  HistoryBranchesClassification </li></a>
    <li><a href="https://portal.korea.ac.kr" class="ping">  ConceptsTheoryTechniques </li></a>
    <li><a href="https://blog.naver.com" class="ping">  By application </li></a>
    <li><a href="https://webtoon.naver.com" class="ping">  Notable economists </li></a>
    <li><a href="https://mail.naver.com" class="ping">  Lists </li></a>
    <li><a href="https://google.co.kr" class="ping">  Glossary </li></a>
    <li><a href="https://en.wikipedia.org/wiki/Game_theory" class="stylish">  Emblem-money.svg Business portal </li></a>
    <li><a href="https://tistory.com" class="stylish">  Bills and coins.svg Money portal </li></a></ul>

<br><br>
    <article> <p>Game theory is the study of mathematical models of strategic interaction among rational decision-makers.[1] It has applications in all fields of social science, as well as in logic, systems science and computer science. Originally, it addressed zero-sum games, in which each participant's gains or losses are exactly balanced by those of the other participants. In the 21st century, game theory applies to a wide range of behavioral relations, and is now an umbrella term for the science of logical decision making in humans, animals, and computers.</p>
      <p>Modern game theory began with the idea of mixed-strategy equilibria in two-person zero-sum games and its proof by John von Neumann. Von Neumann's original proof used the Brouwer fixed-point theorem on continuous mappings into compact convex sets, which became a standard method in game theory and mathematical economics. His paper was followed by the 1944 book Theory of Games and Economic Behavior, co-written with Oskar Morgenstern, which considered cooperative games of several players. The second edition of this book provided an axiomatic theory of expected utility, which allowed mathematical statisticians and economists to treat decision-making under uncertainty.</p>
      <p>Game theory was developed extensively in the 1950s by many scholars. It was explicitly applied to evolution in the 1970s, although similar developments go back at least as far as the 1930s. Game theory has been widely recognized as an important tool in many fields. As of 2014, with the Nobel Memorial Prize in Economic Sciences going to game theorist Jean Tirole, eleven game theorists have won the economics Nobel Prize. John Maynard Smith was awarded the Crafoord Prize for his application of evolutionary game theory.</p></article>
  </body>
</html>

 

Q. #one, #two, ... 이렇게 id를 지정하는데 번거로운 부분이 있었다. id 선택자도 <ol> 태그처럼 순서대로 지정할 수 있는 방법이 있을까?

 

#1-2. 속성을 공부하는 방법

: 속성(property)을 많이 사용하는 순서대로 통계를 보면, 많이 사용되는 속성은 크게 타이포그래피, 색상, 박스 타입 으로 정리된다. 많이 사용되는 것 위주로 공부해 보자.

 

#2. 타이포그래피

: 웹페이지에 쓰이는 글씨에 대한 디자인 서식을 의미

 

1. font-size

여러 단위가 있다(px, em, rem). 지금은 rem 을 권장한다. 이유는?

1) px : 글자 크기 고정. 브라우저의 설정을 변경해도 글씨 크기가 고정됨

2) rem : 글자 크기 가변적. 브라우저의 설정을 변경하면 그에 따라 크기가 변함

ex) rem 은 웹페이지의 [검사(inspect)]를 눌렀을 때 <html>의 폰트 크기와 비례해서 크기가 변한다. 그러나 px는 이에 상관없이 고정된다.

<html>
  <head>
    <meta charset="utf-8">
    <title>beta file</title>
    <style>
      .px{
        font-size:32px ; color:limegreen
      }
      .rem{
        font-size:2rem ; color:orchid
      }
    </style>
  </head>
  <body>
    <article> <p><div class="px">Game theory is the study of mathematical models of strategic interaction among rational decision-makers.[1]</div> <br><div class="px">It has applications in all fields of social science, as well as in logic, systems science and computer science.</div><br> <div class="rem">Originally, it addressed zero-sum games, in which each participant's gains or losses are exactly balanced by those of the other participants.</div><br><div class="rem"> In the 21st century, game theory applies to a wide range of behavioral relations, and is now an umbrella term for the science of logical decision making in humans, animals, and computers.</div></p>
      <p>Modern game theory began with the idea of mixed-strategy equilibria in two-person zero-sum games and its proof by John von Neumann. Von Neumann's original proof used the Brouwer fixed-point theorem on continuous mappings into compact convex sets, which became a standard method in game theory and mathematical economics. His paper was followed by the 1944 book Theory of Games and Economic Behavior, co-written with Oskar Morgenstern, which considered cooperative games of several players. The second edition of this book provided an axiomatic theory of expected utility, which allowed mathematical statisticians and economists to treat decision-making under uncertainty.</p>
      <p>Game theory was developed extensively in the 1950s by many scholars. It was explicitly applied to evolution in the 1970s, although similar developments go back at least as far as the 1930s. Game theory has been widely recognized as an important tool in many fields. As of 2014, with the Nobel Memorial Prize in Economic Sciences going to game theorist Jean Tirole, eleven game theorists have won the economics Nobel Prize. John Maynard Smith was awarded the Crafoord Prize for his application of evolutionary game theory.</p></article>
  </body>
</html>

2. font-color

색깔을 지정하는 방법은 세 가지가 있다.

1) 색깔 이름으로 지정

ex) #ping { color : lightgray }

2) HEX 값으로 지정

ex) h1 { color : #ffffff }

3) RGB 값으로 지정

ex) .dobby { color : rgb(60,60,60) }

 

+) 색깔을 투명하게 지정할 수 있다.

(opacity 라고 표현하기도 함. 0~1의 값. 0 : 투명 <-> 1 : 불투명)

1) 색깔 이름으로 지정  -> 없음(이미 같은 색깔의 다양한 투명도 버전인 색깔들이 많아서 그런 듯)

2) HEX 값으로 지정  -> #RRAAGGBB 형태의 값. (A: alpha(투명도), R : red, G : green, B : blue) 투명도 없는 색상은 AA를 제외한 6자리를 입력하지만, 투명도를 추가하려면 앞에 두 글자를 추가해주면 된다.

ex) #highlight { color : #ff4D6347 }   => 4D 가 투명도를 의미, ff6347 은 색깔을 의미. 

(-> gist.github.com/lopspower/03fb1cc0ac9f32ef38f4 각 투명도에 따라 어떤 글자를 추가하면 되는지 알려줌)

3) RGB 값일 때 지정

ex) .dobby { color : rgb(50,60,30,0.5) }  => 50% 투명한 색깔이 나타남

 

3. text-align

텍스트를 어떻게 정렬할지를 지정. 총 4가지 방법이 있다.

1) 왼쪽 정렬  : text-align:left

2) 가운데 정렬  : text-align:center

3) 오른쪽 정렬  : text-align:right

4) 좌우 간격 동일하게 정렬  : text-align:justify (border 보이게 하면 좌측 우측의 공백이 동일하게 나옴)

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Lorem Ipsum</title>
    <style>
      h2 { color:limegreen ; font-size : 2rem ; text-align:center }
      #left{text-align:left ; border:1px solid lightgreen}
      #center{text-align:center ; background-color:lavenderblush}
      #right{text-align:right ; color:blue}
    </style>
  </head>
  <body>
      <h2>Consierei</h2>
      <p id="left">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur malesuada id nulla vitae consectetur. Quisque pharetra massa vitae enim lobortis, in finibus nibh finibus. Nam laoreet id est quis scelerisque. Etiam fringilla ullamcorper lectus eu scelerisque. In rhoncus convallis posuere. Curabitur sagittis accumsan tellus et interdum. Praesent molestie eros elit, nec rutrum dolor pharetra non. Nulla purus lacus, ultrices sit amet venenatis non, tempor vel enim. Ut fringilla elementum orci, quis auctor tellus ultrices ut. Praesent ut dui sodales, feugiat leo hendrerit, lobortis elit. Donec erat neque, maximus non hendrerit sit amet, scelerisque sagittis arcu. Maecenas sodales in arcu sed lacinia. Maecenas molestie dui ut elit sodales, nec lobortis justo tristique. Nullam pulvinar sapien vitae magna pretium, nec consectetur odio hendrerit.</p>

      <p id="center">Suspendisse vitae nibh pretium, dictum odio vel, laoreet neque. In hac habitasse platea dictumst. Aliquam rhoncus turpis arcu, sed rhoncus eros posuere vel. Integer fermentum vel augue quis auctor. Nunc tellus ante, posuere sodales dignissim vel, bibendum vel libero. Pellentesque imperdiet pellentesque congue. Vivamus ac euismod velit, sodales fringilla risus. Curabitur nunc odio, finibus non dapibus aliquam, molestie et ligula.</p>

      <p id="right">Phasellus eget nulla tellus. Integer eget justo vitae nibh tempor porttitor. Morbi viverra lorem in tellus aliquet, vitae scelerisque tellus luctus. Praesent orci tortor, vestibulum id molestie at, blandit eu nisi. Fusce aliquam orci tellus, in congue sem tempor vitae. Vivamus eget tortor venenatis, venenatis eros nec, dignissim sem. Vestibulum porta tellus orci, sed pharetra ipsum placerat a. Curabitur in justo ex. Nunc commodo, ante quis mattis fermentum, nibh ante dictum orci, at pulvinar eros orci ac massa.</p>

      <p>In ullamcorper lectus in nunc eleifend, vitae laoreet neque dapibus. Sed non leo ut est dapibus tincidunt. Nam vel metus aliquam metus posuere vestibulum et eget ex. Ut tincidunt vulputate risus, id posuere massa faucibus non. Aenean mollis urna non urna volutpat, ut lobortis risus posuere. Sed elementum porta sapien, non pharetra arcu porta sit amet. Sed ultricies nisl accumsan sapien ornare auctor. Nulla commodo tincidunt urna.</p>

      <p>Praesent nec accumsan urna, a cursus urna. Fusce orci felis, maximus ac urna a, vulputate volutpat nulla. Nulla aliquam sem id nisi molestie, vel maximus leo viverra. Mauris id convallis odio, ultrices molestie sem. Aenean sit amet ultricies felis. Vivamus et pharetra turpis, in efficitur metus. Mauris elit diam, mollis ut iaculis sed, lobortis non orci. Vestibulum tempus cursus egestas. Nunc pretium molestie ex. Praesent justo mauris, pharetra sit amet ipsum rhoncus, molestie tempus arcu.</p>
  </body>
</html>

 

+) 웹 프로그래밍 경우, 연습용 텍스트가 많이 필요한 경우가 종종 있다.

이럴 때 사용하면 좋은 사이트: www.lipsum.com/

 

Lorem Ipsum - All the facts - Lipsum generator

What is Lorem Ipsum? Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type spec

www.lipsum.com

의미 없는 텍스트를 대량으로 만들어주는 사이트라 유용하다.

'front-side > CSS' 카테고리의 다른 글

6. 레이아웃 추가(심화)내용  (0) 2021.04.05
5. brackets ~ 레이아웃 기초 내용  (0) 2021.04.02
4. 타이포그래피-font ~ 조화  (0) 2021.04.01
2. 선택자  (0) 2021.03.29
CSS Tutorial:  (1) 2021.03.24

#1. 선택자 공부 팁

선택자의 종류도 많고, 포함관계 등을 따지면 더 복잡하다. 

#1-1. 선택자 공부/연습할 수 있는 사이트 : https://flukeout.github.io

 

CSS Diner

A fun game to help you learn and practice CSS selectors.

flukeout.github.io

: 테이블 안의 음식 중 특정한 것을 고르는 게임? 퀘스트?인데, 그 과정에서 CSS 선택자의 종류와 여러 관계를 학습할 수 있다.

 

 

1. Sibling Selector

1) Adjacent Sibling Selector

A + B

: A와 B가 동일한 level이고(<ul>과 <ol>처럼) A 태그 바로 다음에 B 태그가 언급될 때, B는 A의 adjacent sibling selector이다.

-A 바로 다음에 B가 올 때만 해당

-A 바로 다음에 오는 선택자 하나만 해당

 

2) General Sibling Selector

A ~ B

: A와 B가 동일한 level이고 A 태그 다음에 B 태그가 언급될 때, B는 A의 general sibling selector이다.

-A 바로 다음이 아니어도 A 뒤에 있는 선택자면 모두 해당

-선택자 여러 개 해당

 

 

2. Parent-Child

1-1) Descendant Selector

A  B

: A 선택자 안에 포함된 모든 B 선택자를 선택

-A 선택자 바로 안에 포함된 선택자(direct child)가 아니어도 적용됨

 

1-2) Child Selector

A>B

: A 선택자 바로 안에 포함된 B선택자만 선택

-B 선택자가 A 선택자의 direct child 일 때만 적용됨

 

2) First Child Pseudo Selector

(first-child : 부모 선택자에서 첫 번째로 작성된 자식 선택자를 의미)

:first-child  : 모든 부모 선택자에서 first-child element 선택

A:first-child  : A라는 선택자 안에 포함된 first-child element 선택

A  B:first-child  : A 선택자 안에 포함된 B 선택자 안에 포함된 first-child element 선택

+) A>B:first-child  : A 선택자의 direct child인 B 선택자 안에 포함된 first-child element 선택

 

3) Only Child Pseudo Selector

(only-child : 부모 선택자가 단 하나의 자식 선택자를 가질 때 그 자식을 only child라고 함)

:only-child : 모든 부모 선택자에서 only-child element 선택

A:only-child : A라는 선택자 안에 포함된 only-child element 선택

A  B:only-child : A 선택자 안에 포함된 B 선택자 안에 포함된 only-child element 선택

+) A>B:only-child : A 선택자의 direct child인 B 선택자 안에 포함된 only-child element 선택

 

4) Last Child Pseudo Selector

(last-child : 부모 선택자에서 마지막으로 작성된 자식 선택자를 의미)
:last-child : 모든 부모 선택자에서 last-child element 선택

A:last-child : A라는 선택자 안에 포함된 last-child element 선택

A  B:last-child : A 선택자 안에 포함된 B 선택자 안에 포함된 last-child element 선택

+) A>B:last-child  : A 선택자의 direct child인 B 선택자 안에 포함된 last-child element 선택

 

* first-child , only-child , last-child 는 서로 배타적인 관계가 아니다!

= first-child 이면서 only-child 이면서 last-child 일 수도 있다.

ex) 부모 선택자가 하나의 자식 선택자만 가질 때.

 

+ 선택자가 너무 복잡해서 first-child , only-child , last-child 만으로 표현할 수 없을 때 사용하는 선택자:

5) Nth Child Pseudo-Selector

(nth-child : 부모 선택자에서 n번째로 작성된 자식 선택자를 의미)

:nth-child(a)  : 모든 부모 선택자를 대상으로 a번째 자식 선택자를 선택

A:nth-child(a)  : A라는 부모 선택자를 대상으로 a번째 자식 선택자를 선택

+) A  B 나 A>B 등의 부모-자식 관계를 앞에 적용하는 것도 물론 가능

- 앞에서부터 세는 방식

 

6) Nth Last Child Selector

(nth-last-child : 부모 선택자에서 뒤에서부터 셌을 때 n번째에 있는 자식선택자를 의미)
:nth-last-child(a)  : 모든 부모 선택자를 대상으로 끝에서 a번째 있는 자식 선택자를 의미

+) A  B 나 A>B 등의 부모-자식 관계를 앞에 적용하는 것도 물론 가능

- 뒤에서부터 세는 방식

 

 

3. Type

type : 어떤 태그나 선택자의 종류를 지정할 때 사용

* Type 역시 first, only, last, nth 등으로 종류를 지정한다.

 

1) First of Type Selector

:first-of-type  : 선택자의 종류 상관없이, 같은 선택자 중에서 첫 번째로 제시된 선택자를 의미

A:first-of-type  : A라는 선택자 중에서 첫 번째로 제시된 선택자를 의미

+ 부모-자식관계 적용 가능

 

2) Only of Type Selector

:only-of-type : 같은 선택자인 요소가 없는 경우. 자신만이 해당 선택자일 경우 그 element를 의미

A:only-of-type : A라는 선택자 종류인 유일한 element를 의미

+ 부모-자식관계 적용 가능

 

3) Last of Type Selector

:last-of-type : 선택자의 종류 상관없이, 같은 선택자 중에서 마지막으로 제시된 선택자를 의미

A:last-of-type : A라는 선택자 중에서 마지막으로 제시된 선택자를 의미

+ 부모-자식관계 적용 가능

 

4) Nth of Type Selector

:nth-of-type(a) : 선택자의 종류 상관없이, 같은 선택자 중에서 a번째로 제시된 선택자를 의미

A:nth-of-type(a) : A라는 선택자 중에서 a번째로 제시된 선택자를 의미

A:nth-of-type(odd) : A라는 선택자 중에서 홀수 번째로 제시된 선택자를 의미

+ 부모-자식관계 적용 가능

 

4-1) Nth of Type Selector with Formula

A:nth-of-type(an+b) : A라는 선택자 중에서 b번째부터 시작해서, 매 a번째 element를 의미

ex) li:nth-of-type(3n+2) : <li> 태그 선택자 중에서 2번째부터 시작해서, 매 3번째 element를 의미

(= 2,5,8,11, ... 번째의 li 태그 선택자를 의미)

* nth type selector로도 지칭할 수 없는 선택자가 있을 때 사용하는 것 같다.

 

#1-2. CSS cheat sheet : CSS 공부 중 모르는 점을 찾아볼 수 있는 정리표 개념

구글 이미지검색에 'CSS cheat sheet selector' 라고 검색하면 잘 정리된 표를 찾아볼 수 있다.

 

 

'front-side > CSS' 카테고리의 다른 글

6. 레이아웃 추가(심화)내용  (0) 2021.04.05
5. brackets ~ 레이아웃 기초 내용  (0) 2021.04.02
4. 타이포그래피-font ~ 조화  (0) 2021.04.01
3. 선택자 fin ~ 타이포그래피  (0) 2021.03.30
CSS Tutorial:  (1) 2021.03.24

0. CSS 소개

HTML과 CSS의 관계에 대해 배우던 중 이런 글을 보았다:

 

  • Inline - by using the style attribute inside HTML elements
  • Internal - by using a <style> element in the <head> section
  • External - by using a <link> element to link to an external CSS file

CSS가 HTML 문서에 적용될 수 있는 3가지 방법에 대한 글이다.

1) Inline 방법은 개별 HTML 요소에 style '속성'을 지정하는 방법,

2) Internal 방법은 <style> 태그를 사용하는 방법으로, {}을 사용해서 <p>, <h1> 등 '태그'별로 스타일을 할당할 수 있다.

3) External 방법은 <link> 태그로 외부 파일을 끌어오는 방법인데, CSS 언어를 알아야만 사용가능한 방법이다.

: 실제로 화려한 웹사이트를 보면 대부분 이 방법을 사용해서 적용할 수 없었던 게 아쉬웠다. 이번에 CSS를 배우면서 적용해 보려고 한다!

 

* ctrl + O 키를 누르면 사용중인 브라우저에서 내 컴퓨터의 파일을 불러올 수 있다.

 

1. HTML과 CSS를 연결하는 방법 : style

style : HTML의 태그/속성이고 이제부터 CSS 문법이 사용된다는 것을 알려준다.

1) style 속성

: HTML의 문법에서 style 이라는 '속성'이 있다.

이때 안쪽의 color:skyblue  부분은 CSS 문법이고, 나머지는 HTML 문법이다.

    <h2 style="color:skyblue">Dobby is free!</h2>
    <h2 style="color:skyblue">Dobby is free!</h2>
    <h2 style="color:skyblue">Dobby is free!</h2>

2) style 태그

: HTML의 태그 중 style 태그가 있다. 

이 태그에 둘러싸인 부분에서 CSS 문법이 사용된다는 것을 알려주는 역할을 한다.

장점1: 1) 과 똑같은 결과물이 나오지만, <style> 태그는 특정 태그가 반복될 때 태그별로 다른 서식을 적용시킬 수 있다. 태그가 많을 때 효율적이다.

장점2: <style> 태그는 <head> 태그 안에서 본문의 부연설명으로 쓰인다. 코드상 디자인과 정보 기능을 더 잘 분리시켜서 보여줄 수 있다.

<html>
  <head>
    <style>
      h2 {color:skyblue}
    </style>
  </head>
  <body>
    <h2>Dobby is free!</h2>
    <h2>Dobby is free!</h2>
    <h2>Dobby is free!</h2>
  </body>
</html>

 

2. CSS의 문법 (1) : Selector(선택자) 와 Declaration(선언)

ex) 

    <style>
      h2 {
          color:skyblue;
          text-decoration:underline
          }
    </style>

h2 는 Selector(선택자)이고 디자인 설정을 받을 개체이다.

{  } 안의 부분은 Declaration(선언)이고 Selector에 적용될 디자인 설정이다.

color , text-decoration 부분은 property(속성)이며 Declaration 안의 구체적인 요소들을 의미한다.

skyblue , underline  부분은 value(속성값)이며 property에 할당되는 값이다.

: 은 property와 value를 구분한다.

; 은 각각의 declaration을 구분한다. (declaration이 하나이면 안 써도 된다)

 

그런데 태그 단위로 선언을 하고 싶지 않을 수도 있다.

ex) 여러 <li> 태그 중 하나만 다른 색으로 표시하고 싶을 때

=> 다른 종류의 Selector를 사용하면 된다.

 

사실 Selector에는 세 종류가 있다.

  • Tag Selector : 태그 단위로 선언할 때
  • ID Selector
  • Class Selector

1) ID Selector

: <style> 태그 안에서 ID를 정의한 뒤 따로 다른 선언을 하고 싶은 개체에 해당 ID를 입력하면 된다.

    <style>
      #ping {
        color:#228B22 ; font-size: 30px
      }

    </style>

    <h2 id="ping">Dobby is free!</h2>

 

 # 뒤에는 ID 개체의 이름을 원하는 대로 정해서 입력하고, {  } 안에 디자인 요소를 지정해 준다.

-> 해당 ID Selector를 사용하고 싶으면 해당 개체 속성에 id="Selector 이름"  이런 식으로 지정한다. 

<html>
  <head>
    <style>
      #ping {
        color:#228B22 ; font-size: 30px
      }
      #dobby {
        background-color:LemonChiffon ; font-weight:bold
      }
    </style>
  </head>
  <body>
    <h1 id="ping">CSS</h1>
    <h1>CSS</h1>
      <h2>Dobby is free!</h2>
      <h2 id="dobby">Dobby is free!</h2>
  </body>
</html>

 

2) Class Selector

: <style> 태그 안에서 Class를 정의한 뒤 따로 다른 선언을 하고 싶은 개체에 해당 Class를 입력하면 된다.

 

ID Selector 와의 차이점이 무엇인가?

적용 방법은 거의 비슷하다. 다만 의미에 차이가 있다.

-Class : 여러 학생들을 구분할 때 '반'의 개념. 여러 개체를 '그룹화', '묶어서' 구분할 때 사용

-ID : 학생들 하나하나가 갖는 '고유한' 번호. 고유한 하나의 개체가 하나의 ID를 가짐.

=> Class Selector는 여러 번 사용 가능, ID Selector는 한 번만 사용 가능.

 

또한 class selector는 .dobby  이렇게 class 선언하기 전 . 을 찍는다.

<-> id selector는 #을 붙인다.

<html>
  <head>
    <style>
      #pping {
        color:#228B22 ; font-size: 30px
      }
      .dobby {
        background-color:LemonChiffon ; font-weight:bold
      }
    </style>
  </head>
  <body>
    <h1 id="pping">CSS</h1>
    <h1>CSS</h1>
      <h2>Dobby is free!</h2>
      <h2 class="dobby">Dobby is free!</h2>
      <h2>Dobby is free!</h2>
      <h2 class= "dobby">Dobby is free!</h2>
      <h2>Dobby is free!</h2>
      <h2 class= "dobby">Dobby is free!</h2>
        <h3>welcome</h3>
        <h3>welcome</h3>
  </body>
</html>

+) CSS에는 다양한 종류의 색깔이 있다.

Colors Tutorial (w3schools.com) 여기서 색깔 이름을 볼 수 있다.

 

3. CSS의 문법 (2) : 부모-자식 선택자

ex) <ol>, <ul>, <li> 태그의 경우, <ol>과 <ul> 태그는 <li> 태그를 포함한다.

즉 태그간의 포함관계가 있을 때, 특정 부분의 스타일을 지정하려면 부모-자식 관계를 고려해야 한다.

부모-자식 관계를 고려해서 Style 지정할 수 있는 여러 가지 경우:

 

경우1) 특정 태그 안에 포함되는 다른 태그의 디자인 지정할 때

<html>
  <head>
    <style>
      ol li {
        border-style : solid ; border-color : Salmon ;
        border-radius : 6px ; border-width: 1px
      }
    </style>
  </head>
  <body>
    <ol>
      <li>Window</li>
      <li>Mac OS</li>
      <li>Linux</li>
    </ol>
    <ul>
      <li>iPad</li>
        <ol>
          <li>iPad Air
            <ol>
              <li>iPad Air 3</li>
              <li>iPad Air 4</li>
            </ol>
          </li>
          <li>iPad Pro</li>
        </ol>
      <li>Galaxy Tabs</li>
      <li>Others</li>
    </ul>
  </body>
</html>

=> ol 태그 안에 포함된 li 태그의 경우라면 모두 해당 border 서식이 적용되었다.

 

경우2) 특정 태그의 바로 안에 포함되는 태그한테만 디자인 적용할 때

(아까는 A태그 안에 포함된 B태그라면 무조건 위의 디자인을 적용하는 경우였고, 

지금은 A태그 바로 안에 B태그가 포함된 경우에만 위의 디자인 서식을 적용하는 경우이다.)

cf) 아까 : A태그 안에 C태그, 그 안에 B태그 포함되면 => 적용됨

    지금 : A태그 안에 C태그, 그 안에 B태그 포함되면 => 적용 안 됨

** 만약 같은 종류의 태그인데 한쪽 태그에만 디자인을 적용하고 싶다면, id나 class Selector로 구분시켜 준다.

    <style>
      #tablet li {
        border-style : solid ; border-color : Salmon ;
        border-radius : 6px ; border-width: 1px
      }
    </style>

=> iPad Air 바로 아래의 <ol> 태그에만 id="tablet" 으로 ID Selector를 입력하였고, 이에 따라 해당 <ol> 태그 안에 속한 <li> 태그의 내용에만 디자인 서식이 적용되었다.

 

경우3) 여러 개의 태그에 같은 서식을 적용할 때

* 여러 태그가 포함관계에 있지 않아도 적용된다.

* A태그가 B태그를 포함하고 있는데 A태그에 서식이 적용되면 당연히 B태그에도 서식이 적용된다.

    <style>
       ul, ol {
        border-style : solid ; border-color : ForestGreen ;
        border-radius : 6px ; border-width: 3px
      }
    </style>

=> <ul> 태그와 <ol> 태그 모두 서식이 적용되었고, 둘 다 <li> 태그를 포함하고 있으므로 그 안의 <li>태그에도 개별적으로 서식이 적용되었다.

지금까지 상위 태그에만 적용한 속성이 하위 태그에도 적용된 것은 "상속" 이라는 개념 때문이다.

 

상속(Inheritance)

: 상위 태그(부모 태그) 에서 적용된 속성은 별다른 지시 없이도 하위 태그(자식 태그)에도 그대로 적용된다.

 

 

 

'front-side > CSS' 카테고리의 다른 글

6. 레이아웃 추가(심화)내용  (0) 2021.04.05
5. brackets ~ 레이아웃 기초 내용  (0) 2021.04.02
4. 타이포그래피-font ~ 조화  (0) 2021.04.01
3. 선택자 fin ~ 타이포그래피  (0) 2021.03.30
2. 선택자  (0) 2021.03.29

# 참고한 페이지

1. opentutorials.org/module/552

 

HTML5 태그 사전

표지가 허전해서 임시로 올려봤어요.. ^^ 자매품 CSS Dictionary도 있습니다.

opentutorials.org

2. www.w3schools.com/tags/default.asp

 

HTML Reference

w3schools.com --> THE WORLD'S LARGEST WEB DEVELOPER SITE

www.w3schools.com

 

#0. <abbr> 태그

: 텍스트를 생략어로 지정해주는 태그.

- title 속성을 가진다. <abbr title="풀 네임"> 줄임말 </abbr>  => 주로 이런 식으로 사용한다.

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title></title>
  </head>
  <body>
    <abbr title="acquired immune deficiency syndrome">AIDS</abbr>
    <abbr title="laughing out loud">LOL</abbr>
    <abbr title="too much information">TMI</abbr>
  </body>
</html>

=> 결과물로 텍스트 3개가 나오는데, 각 단어에 커서를 갖다 대면 단어의 풀 네임이 부가설명으로 나온다.

 

1. <address> 태그

: 연락처 정보를 나타내는 태그

<address>
Written by <a href="C:\Users\USER\Desktop\WEB\txt\webpagemaking_1.txt">Lullulu</a>.<br>
Visit us at:<br>
txtborder.com<br>
Sanbon 757, Aricafe<br>
KOREA
</address>

연락처 형식으로 결과물이 나온다. <address> 태그 안의 내용들은 기본값으로 기울임체가 적용된다.

 

#2. <area> 태그

: 이미지의 구체적인 영역을 지정해주는 태그

ex. 하나의 이미지에서 특정 구역을 클릭하면 hyperlink A, 다른 구역을 클릭하면 hyperlink B 이런 식으로 다르게 이동.

area 태그는 map, img 태그와 거의 같이 쓰인다.

사용방법은:

1) 맨 처음에 <img> 로 이미지를 제시하고, usemap 속성으로 map 이름을 정의한다.

2) <map>에서 <img>와 같은 이름을 제시하고, <map> 안에 <area>가 들어간다.

* 한 이미지에서 나누고 싶은 영역 수 만큼 <area> 사용하면 된다.

ex) 한 이미지를 세 구역으로 나누고 싶다 => <area> 태그 3번 사용하면 됨

 

속성:

-shape : 구역의 모양

=> default(사진 전체) / rect(직사각형) / circle(원) / poly(다각형) 이 있음.

-coords : 좌표. 정확히 어느 구역인지를 설명함. 지정한 shape 에 따라 다른 좌표 사용함.

=> rect : (왼쪽 위 점의 X좌표, Y좌표, 오른쪽 아래 점의 X좌표, Y좌표) , 

     circle : (원의 중심 좌표, 반지름) , poly(첫 번째 각의 X좌표, Y좌표, 두 번째 각의 X좌표, Y좌표, 세 번째 각의 X좌표, Y좌표)

-alt : 이미지가 나타나지 않았을 때 부연 설명할 메시지

-href : 해당 영역을 누르면 이동할 url 등의 주소

-target : 새 링크로 이동 시 창이 어디에 열릴지를 설정함.

(늘 _parent 옵션과 _top 옵션이 헷갈렸었는데, 블로그 글 보고 정리했다.)

     - "_parent" : 부모 창에서 열림. 만약 창 A에서 창 B가 열리면, A는 B의 부모 창이다. 그러므로 창 B에서 target을 parent로 설정할 경         우, 창 A에서 새 링크가 열린다.

     - "_top" : 비슷한 개념으로, '최고 부모 창'에서 링크가 열린다. 만약 A에서 B, B에서 C가 나왔고 창 C에서 target을 top으로 설정한다         면, 부모 창 B가 아니라 C의 기준 최고 부모 창인 A에서 새 링크가 열린다. 

     - "_blank" : 새 창에서 링크가 열린다(이때 기존 창은 새 창의 부모 창이 된다).

     - "_self" : 해당 창에서 링크가 열린다.

 

사용예시:

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>web review</title>
  </head>
  <body>
    <abbr title="JohnMat">JMT</abbr> <br>
    <abbr title="RapMonster">RM</abbr>

    <img src="C:\Users\USER\Desktop\WEB\image\france.jpg"  alt="France" usemap="#france" width="600" height="400">

    <map name="france">
      <area shape="rect" coords="0,400,200,0" alt="Blue" href="https://en.wikipedia.org/wiki/Blue">
      <area shape="rect" coords="200,400,400,0" alt="White" href="https://en.wikipedia.org/wiki/White">
      <area shape="rect" coords="400,400,600,0" alt="Red" href="https://en.wikipedia.org/wiki/Red">
    </map>
  </body>
</html>

더 자세한 정보는 www.w3schools.com/tags/tag_area.asp 에 나와 있는데 너무 많아서 정리를 못 했다.

 

#3. <article> 태그

: <p> 가 단락을 구분하는 태그라면, <article>은 문서 내 독립적인 컨텐츠를 나타낸다. 

사용예시: 

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>web review</title>
  </head>
  <body>

    <article>
      <h2>Machine Learning</h2>
      Machine learning (ML) is the study of computer algorithms that improve automatically through experience and by the use of data.[1] It is seen as a part of artificial intelligence. Machine learning algorithms build a model based on sample data, known as "training data", in order to make predictions or decisions without being explicitly programmed to do so.[2] Machine learning algorithms are used in a wide variety of applications, such as email filtering and computer vision, where it is difficult or unfeasible to develop conventional algorithms to perform the needed tasks. <br><br> A subset of machine learning is closely related to computational statistics, which focuses on making predictions using computers; but not all machine learning is statistical learning. The study of mathematical optimization delivers methods, theory and application domains to the field of machine learning. Data mining is a related field of study, focusing on exploratory data analysis through unsupervised learning.[4][5] In its application across business problems, machine learning is also referred to as predictive analytics.
    </article>
    <article>
      <h2>Supervised Learning</h2>
      Supervised learning is the machine learning task of learning a function that maps an input to an output based on example input-output pairs.[1] It infers a function from labeled training data consisting of a set of training examples.[2] In supervised learning, each example is a pair consisting of an input object (typically a vector) and a desired output value (also called the supervisory signal). A supervised learning algorithm analyzes the training data and produces an inferred function, which can be used for mapping new examples. An optimal scenario will allow for the algorithm to correctly determine the class labels for unseen instances. This requires the learning algorithm to generalize from the training data to unseen situations in a "reasonable" way (see inductive bias). This statistical quality of an algorithm is measured through the so-called generalization error.[3]
    </article>
    <article>
      <h2>Unsupervised Learning</h2>
    Unsupervised learning (UL) is a type of algorithm that learns patterns from untagged data. The hope is that through mimicry, the machine is forced to build a compact internal representation of its world. In contrast to supervised learning (SL) where data is tagged by a human, e.g. as "car" or "fish" etc, UL exhibits self-organization that captures patterns as neuronal predelections or probability densities.[1] The other levels in the supervision spectrum are reinforcement learning where the machine is given only a numerical performance score as its guidance, and semi-supervised learning where a smaller portion of the data is tagged. Two broad methods in UL are Neural Networks and Probabilistic Methods.
    </article>

  </body>
</html>

코드가 이런 식으로 나오는데, Machine Learning 글 안에 단락은 <p> 태그로 구분되어 있고, 각 학습(Learning)의 종류는 <article>으로 구분되어 있다.

즉 <p> 보다는 더 컨텐츠를 독립적으로 구분시켜 주는 것이 <article> 태그이다.

<p> : 같은 주제 내에서 단락을 바꿀 때

<article> : 다른 주제로 글을 작성할 때  

 

#4. <aside> 태그

: 중심 컨텐츠와 관련은 있지만 직접적이지 않은 내용을 사이드로 빼서 설명하는 용도의 태그.

* 그런데 aside는 html 문서 상에서는 본문과 차이가 없다.

=> <aside>로 본문과 차이를 주려면, CSS를 사용해서 <style>을 적용해야 한다.

사용예시:

<html>
<head>
<style>
aside {
  width: 30%;
  padding-left: 15px;
  margin-left: 15px;
  float: right;
  font-style: italic;
  background-color: lightgray;
}
</style>
</head>
<body>

<h1>The aside element</h1>

<p>My family and I visited The Epcot center this summer. The weather was nice, and Epcot was amazing! I had a great summer together with my family!</p>

<aside>
<p>The Epcot center is a theme park at Walt Disney World Resort featuring exciting attractions, international pavilions, award-winning fireworks and seasonal special events.</p>
</aside>

<p>My family and I visited The Epcot center this summer. The weather was nice, and Epcot was amazing! I had a great summer together with my family!</p>
<p>My family and I visited The Epcot center this summer. The weather was nice, and Epcot was amazing! I had a great summer together with my family!</p>

</body>
</html>

<style> 태그로 aside 태그에 {}로 속성을 부여했다.

[padding(-left) : (왼쪽)경계와 (왼쪽)글자 사이의 거리 / margin(-left) : (왼쪽) 경계와 다른 컨텐츠 요소 사이의 거리]

그렇다면 정확히 어떻게 <style> 태그로 속성을 부여한다는 것일까?

 

#5. <style> 태그

: 개체의 글자색, 배경색 등 개체의 스타일 정보를 포함시킨다.

주로 CSS를 통해 사용되지만, html 으로도 간단한 스타일 정보는 포함시킬 수 있다.

아래 예시에서 <style> 안의 요소는 변수가 아니라 '태그'이다.

<html>
  <head>
    <style>
    h1 {color:red;}
    p {color:blue;background: green;}
  </style>
  </head>
<body>

  <h1>A heading</h1>
  <p>A paragraph.</p>

</body>

이런 식으로 h1 태그에는 빨간색 글씨체를, p 태그에는 파랑 글씨체와 초록 배경을 <style>로 부여하였다.

=> h1 이랑 p 태그를 사용할 때마다 해당 서식이 적용되어서 나온다.

지금은 <style>에서 태그 단위로 속성을 부여한 것이고, 다른 형식의 데이터에도 style을 부여할 순 있지만 형식이 복잡하고 보통은 CSS에서 많이 이뤄지는 작업이다.

 

만약 태그가 중복되면 어떻게 될까?

: A 태그와 B 태그에 다른 스타일을 할당했는데 해당 본문 내용이 A 태그와 B 태그 둘 모두 안에 포함된다면?

<html>
  <head>
      <style>
        p {color:skyblue;background: pink;}
        article {color: white; background : black}
      </style>
  </head>
  <body>
    
    <p>A paragraph.</p>
    <article>
    Oceans are a crucial part of the biosphere, soaking up carbon dioxide, absorbing more than 90 percent of the excess heat trapped on Earth from carbon emissions and producing half of global oxygen. But as we continue to pump greenhouse gases into the atmosphere, the strain is taking its toll. Action is imperative, but how do we unlock and accelerate ocean-oriented solutions without repeating the mistakes of the past? Join us on March 25 for the debate.
    </article>

    <article>
      <p>
        Every weekday, The Morning newsletter helps millions of readers make sense of the day’s news and ideas. Now, for the first time, join David Leonhardt for a special live edition, created just for subscribers.
      </p>
      <p>
        Hear the latest on the rapidly evolving Covid pandemic directly from public health researchers Ashish Jha of Brown University and Jennifer Nuzzo of Johns Hopkins. They’re here to answer your questions about the latest Coronavirus variants, vaccines and research.
      </p>
    </article>

  </body>
</html>

결과: <article> 태그 안에 <p> 태그가 들어간 부분에서는 <p> 태그의 스타일이 우선적으로 적용된다.

=> 태그가 중첩된 경우, 가장 안에 있는 (본문과 가까운) 태그 스타일이 우선적으로 적용된다.

 

 

 

오늘은 지금까지 배운 태그 및 내용들을 정리해보려고 한다.

 

HTML 문서의 기본 구조

HTML 문서는 최상위 태그인 <html> 태그 안에, 그 다음으로 상위 태그인 <head>와 <body> 태그가 있다.

<head> 태그는 본문에 나타나지는 않지만, 본문의 속성들을 설명해 주는 경우가 많다.

반면 <body> 태그 안에는 본문에 표시되는 내용이 들어간다.

 

예시로 section.blog.naver.com/BlogHome.nhn?directoryNo=0&currentPage=1&groupId=0

네이버 블로그 메인페이지의 html 소스를 살펴보면, 

<head> 태그 안에는 <meta>, <script>, <link>, <title>, <base> 등 특정 태그가 중점적으로 쓰이는 걸 볼 수 있다.

 

여기서 지금 알고 있는 건 <title> 태그와 <base> 태그이다.

<meta> 태그도 사용한 적은 있는데, 안에 속성들이 너무 다양해서 다방면으로 사용하는 방법은 모른다.

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>web review</title>
  </head>
  <body>
    <p>
      Machine learning (ML) is the study of computer algorithms that improve automatically through experience and by the use of data.[1] It is seen as a part of artificial intelligence. Machine learning algorithms build a model based on sample data, known as "training data", in order to make predictions or decisions without being explicitly programmed to do so.[2] Machine learning algorithms are used in a wide variety of applications, such as email filtering and computer vision, where it is difficult or unfeasible to develop conventional algorithms to perform the needed tasks. <br><br> A subset of machine learning is closely related to computational statistics, which focuses on making predictions using computers; but not all machine learning is statistical learning. The study of mathematical optimization delivers methods, theory and application domains to the field of machine learning. Data mining is a related field of study, focusing on exploratory data analysis through unsupervised learning.[4][5] In its application across business problems, machine learning is also referred to as predictive analytics.
    </p>
  </body>
</html>

궁금증)

<html lang="ko"> 와 <meta charset="utf-8"> 의 차이점은 무엇일까?

1) meta charset="utf-8"

: meta 는 다른 데이터를 설명해 주는 데이터를 의미하고, 즉 이 태그는 다른 데이터를 설명할 때 쓰는 태그이다.

charset 는 character set 의 약자로, 문자가 어떤 방식으로 코딩/입력되는지를 의미한다.

charset 에도 여러 종류가 있다. ex) meta charset = "euc-kr" 로 설정하면 한국어, 영어, 일본어만 입력 가능하다.

그런데 utf-8은 유니코드를 위한 문자셋을 의미해서, 웬만한 다국어를 있는 그대로의 문자로 나타낼 수 있다.

2) html lang = "ko"

: html은 가장 최상위 태그이다. html 태그 안의 lang 속성은 해당 문서에서 어떤 언어를 사용할지를 지정한다.

homzzang.com/b/html-156 우리나라는 "ko", 영어는 "en" 등 나라마다 언어 코드가 있다. (왼쪽 링크에서 볼 수 있음)

+ dir = "ltr" 은 무슨 의미?

dir = direction 의 약자. 글자가 입력되는 방향을 의미.

ltr = left to right 를 의미. 즉 글자가 왼쪽에서 오른쪽으로 입력된다는 의미이다!

 

그럼 아까의 예시에서 dir = "rtl" (right to left) 로 설정하면 어떻게 될까?

<!DOCTYPE html>
<html lang="en" dir="rtl">
  <head>
    <meta charset="utf-8">
    <title>web review</title>
  </head>
  <body>
    <p>
      Machine learning (ML) is the study of computer algorithms that improve automatically through experience and by the use of data.[1] It is seen as a part of artificial intelligence. Machine learning algorithms build a model based on sample data, known as "training data", in order to make predictions or decisions without being explicitly programmed to do so.[2] Machine learning algorithms are used in a wide variety of applications, such as email filtering and computer vision, where it is difficult or unfeasible to develop conventional algorithms to perform the needed tasks. <br><br> A subset of machine learning is closely related to computational statistics, which focuses on making predictions using computers; but not all machine learning is statistical learning. The study of mathematical optimization delivers methods, theory and application domains to the field of machine learning. Data mining is a related field of study, focusing on exploratory data analysis through unsupervised learning.[4][5] In its application across business problems, machine learning is also referred to as predictive analytics.
    </p>
  </body>
</html>

이처럼 같은 텍스트를 '오른쪽 정렬' 한 방식으로 출력된다.

'front-side > HTML' 카테고리의 다른 글

새로운 태그 공부  (0) 2021.03.23
18. 웹호스팅 ~ 19. 웹서버 운영하기 + HTML 태그 공부  (0) 2021.03.22
웹 페이지 완성 ~ 원시 웹  (0) 2021.03.19

+ Recent posts