1.길이

 

절대 길이

절대 길이는 고정된 크기 단위로, 다른 요소의 크기에 의해 영향을 받지 않습니다.

  • px ( 1px = 1/96th of 1 inch )

절대 길이이므로 다른 요소의 영향을 받지 않아 화면에서 고정된 크기를 가지지만, 장치의 해상도에 따라 상대적입니다.
여러 환경에서 디자인을 같게 표현하고 브라우저 호환성에 유리한 구조로 되어 있어서,
디자인 의도가 많이 반영된 웹사이트의 경우 픽셀 단위를 사용하는 것을 권장하고 있습니다.

  • pt ( 1pt - 1/72 of 1 inch )

컴퓨터가 없던 시절부터 있던 단위입니다. 
인쇄물이나 워드프로세서 프로그램에서 사용된 가장 작은 표준 인쇄단위입니다. 
웹 화면에 인쇄용 문서를 위한 스타일을 적용할 때 유용하게 사용할 수 있습니다.
그러나 사용하는 기기의 해상도에 따라 차이가 있어 W3C에서도 pt는 웹개발 시 권장하는 단위가 아닙니다.
예를 들면 Windows에서는 9pt = 12px, Mac에서는 9pt = 9px 로 보이게 됩니다.

 

상대 길이

상대 길이는 다른 요소의 크기나 폰트 크기, 브라우저(viewport) 등의 크기에 따라 상대적으로 값이 변합니다.

  • %

        부모의 값에 대해서 백분율로 환산한 크기를 갖게 됩니다.

  • em

        font-size를 기준으로 값을 환산합니다. 소수점 3자리까지 표현 가능합니다.

  • rem

        root의 font-size를 기준으로 값을 환산합니다.

  • vw

        viewport의 width값을 기준으로 1%의 값으로 계산됩니다.

 

2.색깔

    <h1 style="color: red"> heading </h1>
    <h1 style="color: #ff0000"> heading </h1>
    <h1 style="color: #f00"> heading </h1>
    <h1 style="color: rgb(255,0,0)"> heading </h1>    
    <h1 style="color: rgba(255,0,0, 0.5)"> heading </h1>

 

3.배경

  • background-color

      기본 값 : transparent

배경의 색상을 지정하는 속성입니다.
앞선 색상 강의에서 배운 색상 값 적용 방식과 같습니다.

  • background-image

      기본 값 :  none


배경으로 사용할 이미지의 경로를 지정하는 속성입니다.
url의 경로는 절대 경로, 상대 경로 모두 사용 가능합니다.
만약 background-color에 색상이 적용된 상태에서 background-image로 사용된 이미지에 투명한 부분이 있다면,
그 부분에 background-color 색상이 노출됩니다.

  • background- repeat

    기본 값 : repeat

이미지의 반복 여부와 방향을 지정하는 속성입니다.
기본값이 repeat이기 때문에 따로 설정하지 않으면 x, y축으로 반복되어서 표시됩니다.
background-repeat의 값으로 사용할 수 있는 것들은 다음과 같습니다.

 

< 속성 값 >

repeat

x, y축 으로 모두 반복합니다.

repeat-x

x 축 방향으로만 반복합니다.

repeat-y

y 축 방향으로만 반복합니다.

no-repeat

이미지를 반복하지 않습니다.

 

  • background-position 기본 값 : 0%  0% 요소에서 배경 이미지의 위치를 지정하는 속성입니다.  x축, y축으로부터의 위치를 지정할 수 있으며, 값의 선언 순서는 x축, y축으로부터의 간격입니다. 만일 한쪽만 지정된다면 나머지는 중앙 값(center)으로 적용됩니다.

 

< 속성 값 >

%

기준으로부터 % 만큼 떨어진 지점과 이미지의 % 지점이 일치하는 곳에 위치시킵니다.

px

기준으로부터 px 만큼 떨어진 지점과 이미지의 (0,0) 지점이 일치하는 곳에 위치시킵니다.

키워드

top, left, right, bottom, center 키워드를 사용할 수 있습니다.

키워드는 선언 순서와 관계없이 top, bottom은 y축 기준으로 하며 left, right는 x축을 기준으로 합니다.

  

  • background-attachment 기본 값 : scroll 화면 스크롤에 따른 배경 이미지의 움직임 여부를 지정하는 속성입니다.

 

< 속성 값 >

scroll

배경 이미지는 요소 자체를 기준으로 고정되어 있으며 내용과 함께 스크롤 되지 않습니다.

local

배경 이미지는 요소의 내용을 기준으로 고정되어 있으며 내용과 함께 스크롤 됩니다.

fixed

배경 이미지는 뷰포트를 기준으로 고정되어 있으며 스크롤에 영향을 받지 않습니다.


4.박스모델1

     Content 영역

       요소의 실제 내용을 포함하는 영역입니다. 따라서 크기는 내용의 너비 및 높이를 나타냅니다.

  • Border 영역

    content 영역을 감싸는 테두리 선을 border라고 합니다.
  • Padding 영역

    content 영역과 테두리 사이의 여백을 padding이라고 합니다.
    content 영역이 배경, 색 또는 이미지가 있을 때 패딩 영역까지 영향을 미칩니다.
    이에 따라 padding을 content의 연장으로 볼 수도 있습니다.
  • Margin 영역

    border 바깥쪽의 영역을 margin이라고 합니다.
    border 영역을 다른 요소와 구별하기 위해 쓰이는 빈 영역입니다.
    즉, 주변 요소와의 여백(간격)을 margin을 이용해 지정할 수 있습니다.

5.border 속성

border-width

기본 값 : medium 선의 굵기를 지정하는 속성입니다. border-top-width, border-bottom-width, border-right-width, border-left-width를 이용하여 상하좌우 선의 굵기를 다르게 표현할 수 있습니다.

 

border-style 기본 값 :  none 선의 모양을 지정하는 속성입니다. border-top-style, border-bottom-style, border-right-style, border-left-style을 이용하여 상하좌우 선의 모양을 다르게 표현할 수 있습니다.

 

**

none

border를 표시 하지 않습니다.

solid

border를 실선 모양으로 나타냅니다.

double

border를 이중 실선 모양으로 나타냅니다.

dotted

border를 점선 모양으로 나타냅니다.


6. Padding

padding: [-top] [-right] [-bottom] [-left];

0 10px 20px 30px /* 상, 우, 하, 좌 다름 */

0 10px 20px /* 좌, 우 같음 */

0 10px /* 상, 하 같음 & 좌, 우 같음 */

0 /* 상, 우, 하, 좌 모두 같음 *

 


7.Margin

  • margin auto 기본적으로 브라우저에 의해 계산이 이루어지는데, 대부분의 경우 0(기본값) 또는 요소의 해당 측면에서 사용 가능한 공간과 같은 값을 가집니다. 이를 활용하여 수평 중앙 정렬을 할 수 있습니다. 아래 코드를 살펴봅시다.

 

 

*margin과 padding의 비교

 

       +       

       -       

    auto    

       단위

margin

       o

       o

       o

    px, % ...   

padding

       o

       x

       x

    px, % ...

 

  • 음수값 사용 가능 여부! 왜 margin은 음수 값 적용이 가능하고, padding은 적용되지 않을까요? 예를 들어 생각해보자면, padding은 뼈와 우리 피부 사이의 지방이라고 생각하고, margin은 사람과 사람 사이의 간격이라고 생각하면 쉽습니다. 지방은 아무리 뺀다고 해서 피부가 뼈보다 밑으로 갈 수 없을 뿐만 아니라, 0 이하가 될 수 없으므로 양수만 된다고 생각하면 됩니다. 그러나 사람과 사람 사이는 멀리 떨어질 수도 있지만, 서로 겹쳐서 서 있을 수도 있으므로 음수 값이 가능하다고 생각하면 됩니다.
  • %값의 사용과 기준점 css 속성을 사용하면서 어떤 값을 적용할 때 이 단위를 적용 할 수 있을까? 라는 생각을 가지고 코딩하는 자세는 매우 중요합니다. margin과 padding은 px과 같은 고정적인 단위 외에도 %라는 상대적인 단위를 사용 할 수 있습니다. %는 요소의 크기를 기준으로 상대적인 값을 결정짓게 됩니다. 얼핏 생각하면, 상하는 height 값에 대해 좌우는 width 값에 대해 크기가 계산될 거 같지만 그렇지 않습니다. %는 상하좌우의 방향에 관계없이 모두 요소의 width 값을 기준으로 값이 결정 됩니다.

div { width: 100px; height: 200px; margin: 10%; padding: 10%; }

만약 위와 같은 코드의 경우에는 margin과 padding이 모두 20px 10px 20px 10px으로 적용되는 것이 아니라,  10px 10px 10px 10px 값으로 적용됩니다.

 


8.Width && Height

 

width 속성

      기본 값 : 0

 

< 속성 값 >

auto

브라우저에 의해 자동으로 계산하여 적용합니다. * 요소의 레벨 기본 특성에 따라 다르게 동작합니다.

length

고정값으로 지정합니다. (ex. px, em ....)

percent

부모 요소의 width에 상대적인 크기를 지정합니다.

width는 content 영역의 너비를 제어할 때 사용하는데 이때 auto가 아닌 특정한 값을 지정하여 사용하면,

그 크기는 box model 영역에서 margin 영역을 제외한 모든 영역에 대해 영향을 받습니다. (content, padding, border) 

예를 들어,

<div class="box"> box </div>
 
.box {
  width: 100px;
  padding: 20px;
  border: 10px solid black;
}

위와 같이 선언되어있다면 요소의 총 가로 크기는 160px가 됩니다.

분명 width: 100px를 적용했는데 어떻게 160px가 된 걸까요?

앞선 설명에서 언급한 바와 같이 width는 padding, border 영역에 대해서 영향을 받기 때문입니다.

1.CSS 적용

1. Inline

Inline은 해당 요소에 직접 스타일 속성을 이용해서 규칙들을 선언하는 방법입니다.

해당 요소에 직접 입력하기 때문에 선택자는 필요하지 않게 되고, 선언부에 내용만 스타일 속성의 값으로 넣어주면 됩니다.

Inline 스타일 방식이라고 부릅니다.

<div style="color:red;"> 내용 </div>

<div style="color:red;"> 내용 </div>

Inline 스타일 방식은 코드의 재활용이 되지 않기 때문에 자주 사용하지 않습니다.

 

2. Internal

Internal은 문서에 <style>을 활용한 방법입니다.

<style> <head>내부에 들어가며 <style>안에 스타일 규칙이 들어갑니다.

<style> div {color: red;} </style>

<style> div {color: red;} </style>

위의 코드로 모든 <div>에 같은 스타일을 줄 수 있습니다.

하지만 이것도 한계가 있습니다.

많은 페이지가 있는 경우에는 모든 페이지에 저마다의 규칙을 선언해줘야 합니다.

페이지가 많고 스타일 규칙 내용이 많아지면 결코 쉬운 일은 아닙니다.

 

3. External

External은 외부 스타일 시트 파일을 이용한 방법입니다.

외부 스타일 시트는 스타일 규칙들을 별도의 외부 파일을 만들어 넣는 방식입니다.

외부 파일은 확장자가 .css가 되며 css 파일이라고 부릅니다.

div {color: red;}

div {color: red;}

우선 CSS 파일을 하나 만들고 스타일 규칙을 선언합니다.

그다음 <link>을 이용해서 CSS 파일을 연결하면 됩니다.

<link rel="stylesheet" href="css/style.css">

<link rel="stylesheet" href="css/style.css">

<head> 내부에 <link>를 선언한 후 href 속성을 이용해 CSS 파일의 경로를 적습니다.

rel 속성은 연결되는 파일이 문서와 어떤 관계인지를 명시하는 속성으로, CSS 파일은 'stylesheet' 라고 적어야 합니다.

외부 스타일 시트 방식으로 스타일을 선언하면 많은 페이지가 있더라도 이 한 줄로 모든 페이지에 같은 스타일을 적용할 수 있습니다.

또한, 수정이 필요할 때도 CSS 파일을 수정하면 연결된 모든 페이지에 반영할 수 있습니다.

외부 스타일 시트 방식은 파일 관리가 편하면서도 용량이 작기 때문에 주로 사용되는 방법입니다.

 

4. Import

Import는 스타일 시트 내에서 다른 스타일 시트 파일을 불러오는 방식입니다.

@import url("css/style.css");

@import url("css/style.css");

<style> 내부 상단이나 외부 스타일 시트 파일 상단에 선언하는데 성능상 좋지 않아서 거의 쓰이지 않습니다.

이에 본 강의에서는 다루지 않습니다. 궁금하신 분들은 따로 찾아보시길 바랍니다.


2.그룹화

* { color: yellow; }

* { color: yellow; }

h1, h2, h3, h4, h5, h6 { color: yellow; }

 

 

3.선택자

 

-CLASS

<dl>
    <dt class="html">HTML</dt>
    <dd><span class="html">HTML</span>은 문서의 구조를 나타냅니다.</dd>
    <dt class="css">CSS</dt>
    <dd><span class="css">CSS</span>는 문서의 표현을 나타냅니다.</dd>
</dl>


//CSS

.html { color: purple; }
.css { text-decoration: underline; }

다중선택자
.foo { font-size: 30px; }
.bar { color: blue; }

<p class="foo bar"> ... </p>

 

-ID

<p id="bar"> ... </p>

#bar { background-color: yellow; }

 

class 선택자와의 차이점

  1. .기호가 아닌 #기호 사용
  2. 태그의 class 속성이 아닌 id 속성을 참조
  3. 문서 내에 유일한 요소에 사용
  4. 구체성 

가장 큰 차이점은 class와 달리 id는 문서 내에서 유일해야 한다는 점입니다.

클래스 선택자는 여러 요소에 같은 클래스를 넣고 같은 규칙을 적용 할 수 있었습니다.

 


4.선택자2

/* 요소와 class의 조합 */
p.bar { ... }

/* 다중 class */
.foo.bar { ... }

/* id와 class의 조합 */
#foo.bar { ... }


//정확한 속성값 지칭
p[class="foo"] { color: silver; }
p[id="title"] { text-decoration: underline; }

 

<p class="color hot">red</p>
<p class="cool color">blue</p>
<p class="colorful nature">rainbow</p>

p[class~="color"] { font-style: italic; } /* 1, 2번째 요소 */
p[class^="color"] { font-style: italic; } /* 1, 3번째 요소 */
p[class$="color"] { font-style: italic; } /* 2번째 요소 */
p[class*="color"] { font-style: italic; } /* 1, 2, 3번째 요소 */

//
[class~="bar"] : class 속성의 값이 공백으로 구분한 "bar" 단어가 포함되는 요소 선택
[class^="bar"] : class 속성의 값이 "bar"로 시작하는 요소 선택
[class$="bar"] : class 속성의 값이 "bar"로 끝나는 요소 선택
[class*="bar"] : class 속성의 값이 "bar" 문자가 포함되는 요소 선택
//

5.자손, 부모 선택자

//자손 선택자
div span { color: red; }

//자식 선택자
div > h1 { color: red; }

//인접 형제 선택자
div + p { color: red; }

6. 가상클래스(특정한 조건을 만족해야 선택함)

/*
:first-child : 첫 번째 자식 요소 선택
:last-child : 마지막 자식 요소 선택
*/

<ul>
    <li>HTML</li>
    <li>CSS</li>
    <li>JS</li>
</ul>

li:first-child { color: red; }
li:last-child { color: blue; }



/*
:link : 하이퍼 링크이면서 아직 방문하지 않은 앵커
:visited : 이미 방문한 하이퍼링크를 의미
*/

a:link { color: blue; }
a:visited { color: gray; }

/*
:focus: 현재 입력 초점을 가진 요소에 적용
:hover: 마우스 포인터가 있는 요소에 적용
:active: 사용자 입력으로 활성화된 요소에 적용
*/

a:focus { background-color: yellow; }
a:hover { font-weight: bold; }
a:active { color: red; }

7. 구체성

important

important 키워드는 별도의 구체성 값은 없지만, 모든 구체성을 무시하고 우선권을 갖습니다.

important 키워드는 속성값 뒤 한 칸 공백을 주고 느낌표 기호와 함께 씁니다.

p#page { color: red !important; }

8.상속

 

상속된 CSS는 구체성을 가지지 못하기 때문에 구체성을 가진 전체 선택자의 스타일이 적용이된다

 

* { color: red; }
h1#page { color: gray; }

<h1 id="page">Hello, <em>CSS</em></h1>

//이러면 em에는 gray가 들어감

박스 모델 관련 속성들은 상속되지 않는다. ex)margin, padding,background,border...

1.시멘틱 마크업

<b>굵은</b> vs <strong>중요한</strong>
<i>기울어진</i> vs <em>강조하는</em>
<u>밑줄친</u> vs <ins>새롭게 추가된</ins>
<s>중간선이 있는</s> vs <del>삭제된</del>

위 코드를 작성해서 화면을 보면 각각의 요소가 같은 모습으로 표현되나 그 의미가 같지는 않습니다.

<b>는 의미 없이 단순히 텍스트를 굵게 표현하는 태그지만, <strong>은 중요하다는 의미를 지닙니다.

<strong>은 중요하다는 의미에 맞춰 브라우저에 의해 굵은 스타일로 표현된 것입니다.

따라서 중요하다는 의미를 포함할 때는 <b>가 아닌 <strong>을 사용하는 것이 적절하고 시멘틱한 마크업입니다.

 

이외에 <i>는 단순히 기울어진 글자를 표현하지만, <em>은 글자의 특정 부분을 강조하는 의미를 지닙니다.

<u> <s>는 단순히 글자에 선을 그은 것이고, <ins> <del>은 내용이 새롭게 추가되거나

삭제가 되었다는 의미를 지닙니다.

 

 

2.추가 태그

  • <article> : 본문의 주 내용이 들어가는 공간을 의미
  • <aside> : 내부에 위치하는 내용이 외에 사이드에 손재하는 내용을 의미
  • <figcaption> : <figure> 태그의 캡션(설명)을 정의한다.
  • <figure> : 그림이나 도표, 사진과 같은 독립적인 콘텐츠들을 명시
  • <footer> : 문서, 구역의 바닥 글을 정의
  • <header> : 소개 내용이나, 목록과 같은 링크들의 묶음을 표시
  • <main> : 문서의 주요 내용을 지정할 대 사용한다. 단, 고유한 내용만을 지정할 수 있고 반복되는 내용을 포함해서는 안된다.
  • <mark> : 텍스트의 일부를 강조
  • <nav> : 문서 네의 링크들의 집합, 내비게이션을 의미
  • <section> : 문서의 구역을 정의
  • <time> : 특정 시간이나 날자를 정의

  • <article> : 내용을 내부에서 구분하여 정의 내림 
  • <aside> : 주요 내용과 간접적으로만 연관된 부분 표현, 사이드바 혹은 콜아웃 박스로 주로 표현 
  • <figcaption> : <figure> 내 콘텐츠에 대한 설명/범례
  • <figure> : 독립적인 콘텐츠를 표현
  • <footer> : 꼬릿말(구획의 작성자, 저작권 정보, 관련 문서)
  • <header> : 머릿말(소개 및 탐색을 위한 제목(h1~2) 시멘틱 마크업)
  • <main> : 본문,  주요 콘텐츠
  • <mark> : 현재 맥락에 관련이 깊거나 중요한 부분 하이라이트
  • <nav> : 문서의 부분 중 현재 페이지 내, 또는 다른 페이지로의 링크를 보여주는 구문 생성(<li> 활용)
  • <section> : 내용을 내부에서 구획화
  • <time> : 시간의 특정 지점 또는 구간 표현, datetime 이라는 특성으로 유효한 날짜 구문 마크업 가능

 

3.block vs inline

block level : 한 줄에 하나의 요소 표시

ex) div,h1~h6, p, ul, li, table 등

inline level : 한 줄에 여러개 요소 표시 가능

ex) span, i, img, em, strong 등

'일상 > HTML5, CSS3' 카테고리의 다른 글

Boostcourse[웹UI] 5.단위, 배경, 박스모델  (0) 2021.01.13
Boostcourse[웹UI] 4.CSS이해하기  (0) 2021.01.12
BoostCourse[웹UI] 2. HTML태그  (0) 2021.01.12
2.Styling Page Sections  (0) 2017.10.01
1. Css for Styling  (0) 2017.10.01

1.테이블

<table>

    <caption>Monthly Savings</caption>
    <thead>
        <tr>
            <th>Month</th>
            
<th>Savings</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            
<td>January</td>
            <td>$100</td>
        </tr>
        <tr>
            
<td>February</td>
            <td>$80</td>
        </tr>

    </tbody>
    <tfoot>
        <tr>
            
<td>Sum</td>
            <td>$180</td>
        </tr>
    </tfoot>

</table>
 
 <table>
  <caption>Specification values</caption>
  <thead>
  <tr>
    <th rowspan="2">Grade.</th>
    <th rowspan="2">Point.</th>
    <th colspan="2">Strength.</th>
    <th rowspan="2">Percent.</th>
  </tr>
  <tr>
    <th>kg/mm</th>
    <th>lb/in</th>
  </tr>
  </thead>
  <tbody>
  <tr>
    <td>Hard</td>
    <td>0.45</td>
    <td>56.2</td>
    <td>80,000</td>
    <td>20</td>
  </tr>
  <tr>
    <td>Medium</td>
    <td>0.45</td>
    <td>49.2</td>
    <td>70,000</td>
    <td>25</td>
  </tr>
  <tr>
    <td>Soft</td>
    <td>0.45</td>
    <td>42.2</td>
    <td>60,000</td>
    <td>30</td>
  </tr>
  </tbody>
</table>

-colspan : 가로셀 합치기

-rowspan : 세로셀 합치기

 

 

2.input요소

<input type="text" placeholder="ㅇㅇㅇ">

<input type="password">

<input type="radio" name="gender"> 남자
<input type="radio" name="gender"> 여자

<input type="checkbox" name="hobby"> 등산
<input type="checkbox" name="hobby"> 독서
<input type="checkbox" name="hobby"> 운동

<input type="file">

<form action="./test.html">
    메시지: <input type="text" name="message"><br>
    <input type="submit">
    <input type="reset">
    <input type="image" src="http://placehold.it/50x50?text=click" alt="click" width="50" height="50">
    <input type="button" value="버튼">
</form>

-radio는 name태그가 같아야 서로 상호작용 가능

-checkbox도 name으로 묶어줘야 함. 그래야 값을 받아올 수 있음

-submit은 제출, reset은 초기화

-button 타입은 custom해줘야 함 value로 이름 변경 가능

-image 타입은 이미지 버튼임. alt, src 필수

 

 

3.select

<select>
    <option>서울</option>
    <option>경기</option>
    <option selected>강원</option>
    ...
</select>


<textarea rows="5" cols="30" placeholder="안녕">
    ...
</textarea>

<button type="submit|reset|button">ㅇㅇㅇ</button>

-option에 selected 타입을 주면 처음에 선택되어 있음

-input type=button이랑 button태그랑은 다름

 

4.else form

<label for="name">이름</label>: <input type="text" id="name"><br>
<label for="nickname">이름</label>: <input type="text" id="nickname"><br>
<label for="address">이름</label>: <input type="text" id="address"><br>

<fieldset>
    <legend>기본 정보</legend>
    ... 폼 요소들 ...
</fieldset>
<fieldset>
    <legend>부가 정보</legend>
    ... 폼 요소들 ...
</fieldset>

<form action="" method="">
    <fieldset>
        <legend>기본 정보</legend>
        ... 폼 요소들 ...
    </fieldset>
    <fieldset>
        <legend>부가 정보</legend>
        ... 폼 요소들 ...
    </fieldset>
</form>

-fieldset으로 구조화 해줌. 묶어준다고 생각하면 됨

-legend는 구조화한것의 제목 설정

-Form 태그는 action에는 데이터 처리 주소 / method는 get이나 post처럼 어떻게 보낼건지?

 

5.전체 코드

<!DOCTYPE html>
<html lang="ko">
<head>
	<meta charset="UTF-8">
	<title>form</title>
</head>
<body>
	<form action="">
		<h1>Form 관련 요소</h1>
		<fieldset>
			<legend>기본 정보</legend>
			<label for="userid">아이디 : </label> <input type="text" placeholder="영문으로만 써주세요" id="userid"><br>
			<label for="userpw">비밀번호 : </label> <input type="password" id="userpw"><br>
			성별 : <label for="male">남자</label> <input type="radio" name="gender" id="male" checked>, <label for="female">여자</label> <input type="radio" name="gender" id="female"><br>
		</fieldset>
		<fieldset>
			<legend>부가 정보</legend>
			취미 : 영화 감상 <input type="checkbox" name="hobby" checked>, 음악 감상 <input type="checkbox" name="hobby">, 독서 <input type="checkbox" name="hobby"><br>
			프로필 사진 업로드 : <input type="file"><br>
			사는 지역 : <select>
				<option>서울</option>
				<option>경기</option>
				<option>강원</option>
				<option selected>제주</option>
			</select><br>
			자기소개 : <textarea cols="30" rows="5" placeholder="자기소개는 짧게 해주세요."></textarea><br>
			<button type="submit">전송</button>
			<button type="reset">취소</button>
		</fieldset>
	</form>
</body>
</html>

'일상 > HTML5, CSS3' 카테고리의 다른 글

Boostcourse[웹UI] 4.CSS이해하기  (0) 2021.01.12
Boostcourse[웹UI] 3.콘텐츠모델, 시멘틱마크업, 블록 & 인라인  (0) 2021.01.12
2.Styling Page Sections  (0) 2017.10.01
1. Css for Styling  (0) 2017.10.01
2.Basic HTML  (0) 2017.09.30

4.0 Introduction to the Movie DB API

 

-API 키 받아오기

 

 

4.1 Sexy Networking with Axios Instances

//src에 api.js만들어줌
//yarn add axios 해주기

import axios from "axios";

const api = axios.create({
  baseURL: "https://api.themoviedb.org/3/",
  params: {
    api_key: "752f18d6d4ff8f2972e298adcbc4af9b",
    language: "en-US"
  }
});

export default api;

//기본 API주소에서 파라미터들 원하는거 주고 Axios로 받아오는거임

 

 

4.2 API Verbs Part One

export const moviesApi = {
    nowPlaying: () => api.get("movie/now_playing"),
    upcoming: () => api.get("movie/upcoming"),
    popular: () => api.get("movie/popular")
  };
  
export const tvApi = {
    topRated: () => api.get("tv/top_rated"),
    popular: () => api.get("tv/popular"),
    airingToday: () => api.get("tv/airing_today")
  };
  
  //API 불러오기

 

4.3 API Verbs Part Two 

 

export const moviesApi = {
    nowPlaying: () => api.get("movie/now_playing"),
    upcoming: () => api.get("movie/upcoming"),
    popular: () => api.get("movie/popular"),
    movieDetail: id =>
      api.get(`movie/${id}`, {
        params: {
          append_to_response: "videos"
        }
      }),
    search: term =>
      api.get("search/movie", {
        params: {
          query: encodeURIComponent(term)
        }
      })
  };
  
export const tvApi = {
    topRated: () => api.get("tv/top_rated"),
    popular: () => api.get("tv/popular"),
    airingToday: () => api.get("tv/airing_today"),
    showDetail: id =>
      api.get(`tv/${id}`, {
        params: {
          append_to_response: "videos"
        }
      }),
    search: term =>
      api.get("search/tv", {
        params: {
          query: encodeURIComponent(term)
        }
      })
  };
  //조금 추가해서 search기능 만들었음.

'일상 > React' 카테고리의 다른 글

React 공부 (복습, 오답노트)  (0) 2021.01.13
React 공부 (with nico 3장)  (0) 2021.01.07
React 공부 (with nico 2장)  (0) 2021.01.07
React 공부 (with nico 1장)  (0) 2021.01.06
React 공부 (with reactjs.org 2)  (0) 2021.01.05

3.0 CSS in React part One

 

//style.css를 index.js랑 같은 곳에 만들어 준다.

//Header.js를 Components안에 Header 폴더를 만들고 그안에 넣고 새로 index.js를 만들자
//내용은
import Header from "./Header";

export default Header;

//style.css를 header 폴더에 옮기고 나서 header.css로 변경해줌
.nav ul {
    display : flex;
}
//내용은 이렇게 쓰면 컴포넌트 폴더 안에 Header 폴더에 header.css, index.js, header.js가 한몸임

 

3.1 CSS in React part Two

// 좀더 한몸이 되게 해보기

//header.css를 header.module.css로 바꾸기
//그럼 header.js에서 import를 import styles from "./Header.module.css"; 해주기

//css파일에
.navList {
    display : flex;
}

//js에서는 이렇게 씀
    <header className={styles.navList}>

//그럼 다른 파일에서도 navList를 쓸 수 있음

 

3.2 CSS in React part Three

 

// 이번에는 header 파일이 필요없는 그런 걸 해볼거임 일단 header.js를 밖으로 빼고 다지우자

//yarn add styled-components

//import 추가하기
import style from "styled-components" 

//header.js를 이렇게 작성함 LIST는 이제 어디서든 쓰기가능
import React from "react";
import { Link } from "react-router-dom";
import styled from "styled-components";

const Header = styled.header``;

const List = styled.ul`
  display: flex;
  &:hover {
    background-color: blue;
  }
`;

const Item = styled.li``;

const SLink = styled(Link)``;

export default () => (
  <Header>
    <List>
      <Item>
        <SLink to="/">Movies</SLink>
      </Item>
      <Item>
        <SLink to="/tv">TV</SLink>
      </Item>
      <Item>
        <SLink to="/search">Search</SLink>
      </Item>
    </List>
  </Header>
);

//이후에 라우터안에 header 넣어주기

 

3.3 GlobalStyles and Header

//이번에는 css를 글로벌하게 해보자
//yarn add styled-reset --> 초기화

나머지는 따라씀
globalsytle 추가하고 끝

 

3.4 Location Aware Header

 

//withRouter는 다른 라우터를 감싸는 라우터임

'일상 > React' 카테고리의 다른 글

React 공부 (복습, 오답노트)  (0) 2021.01.13
React 공부 (with nico 4장)  (0) 2021.01.08
React 공부 (with nico 2장)  (0) 2021.01.07
React 공부 (with nico 1장)  (0) 2021.01.06
React 공부 (with reactjs.org 2)  (0) 2021.01.05

2.0 Setting up the Project

 

//파일 만들기
npx create-react-app JIWON(이름)

//그리고 App.js, index.js빼고 다 지우기

//index.js 내용
import React from 'react';
import ReactDOM from 'react-dom';
import App from './Components/App';

ReactDOM.render(<App />, document.getElementById("root"));


//App.js내용
import React, {Component } from "react";

class App extends Component {
	render() {
    	return <div className="App" />;
    }
}

//이후에 yarn add prop-types

 

 

2.1 React Router Part One

//yarn add react-router-dom 으로 돔 다움받기

//src안에 Components라는 폴더 만들고 Router.js + App.js 두개 넣기

// 나머지 파일들은 src및에 Routes라는 폴더 안에 있음

//App.js안에 render안에 return안에 어떤것을 보여줄지 1개의 컴포넌트로 넣어주셈

//Router.js를 만들고

import React from "react";
import {BrowserRouter as Router, Route, Redirect, Switch} from "react-router-dom";
import Home from "../Routes/Home";
import TV from "../Routes/TV";
import Search from "../Routes/Search";

export default () => (
    <Router>
        <Switch>
            <Route path="/" exact component={Home} />
            <Route path="/tv" exact component={TV} />
            <Route path="/tv/popular" render={() => <h1>PoPULAR</h1>} />
            <Route path="/search" exact component={Search} />
            <Redirect from="*" to="/" />
        </Switch>
    </Router>
);
//이런느낌으로 만들기

 

 

2.2 React Router Part Two

//Components에 Header.js 만들기 (이게 위에 슬라이드 인듯)

//내용은 이렇게

import React from "react";

export default () => (
    <header>
        <ul>
            <li>
                <a href="/">Movies</a>
            </li>
            <li>
                <a href="/TV">TV</a>
            </li>
            <li>
                <a href="/Search">Search</a>
            </li>
        </ul>
    </header>
)

//그리고 위에 2.1의 코드에서 Redirect는 아무것도 일치하지 않으면 저기로 가게 해둔다는 의미임
//exact붙이면 무조건 똑같이 타이핑 해야된다는거고

'일상 > React' 카테고리의 다른 글

React 공부 (with nico 4장)  (0) 2021.01.08
React 공부 (with nico 3장)  (0) 2021.01.07
React 공부 (with nico 1장)  (0) 2021.01.06
React 공부 (with reactjs.org 2)  (0) 2021.01.05
React 공부 (with reactjs.org)  (0) 2021.01.05

1.1 Arrow Function

- 화살표 함수를 쓰면 return을 안써도 됨

 

- 인자가 한개일때는 괄호를 안써도 됨

 

const sayHello = (name="Human") => "Hello" + name

const nico = sayHello();

console.log(nico);

button.addEventListener("click", event => console.log(event));

 

 

1.2 template Literals

-`` 잘쓰기, 변수는 ${변수} 이렇게 넣어줌 좀 더 간편하게 나타냄

 

const sayHello = (name) => `Hello ${name}`;

 

 

1.3 Object Destructuring

-좀 더 변수를 효율적으로 담는 방법

 

const human ={
	name : "jiwon",
    lastName : "kim",
    nation : "korea",
    favFood : {
    	break : "hey",
        lunch : "two",
        dinner : "three"
    }
}

//비효율적
const name = human.name

//효율
const {name, lastName, nation:nana, favFood :{break, lunch, dinner}} = human;

console.log(name, lastName, nana);

 

 

1.4 Spread Operator

- 이렇게 unpack해서 배열에 넣어주어야함. [], {} 둘다 가능

 

const Days = ["Mon", "Thu", "Wed"];
const otherDays = ["Tue", "Fri", "Sat"];

//두개를 합치려면
const allDays = [...days, ...otherDays];

console.log(allDays);

 

1.5 Classes

-객체지향을 따름 --> 상속 가능

 

class Human{
	constructor (name, lastName){
    	this.name = name;
        this.lastName = lastName;
    }
}

class Baby extends Human{
	cry(){
    	console.log("Waaaa");
    }
    sayName(){
    	console.log(`My name is ${this.name}`)
    }
}

const myBaby = new Baby("mini","me");

console.log(myBaby.cry(), myBaby.sayName());

 

1.6 Arrow map

-array를 전체적으로 바꿀때는 이렇게 map을 사용하면 좋음

 

cosnt days = ["M","T","W","T","F"];

//Smile 추가하기
const addSmile = day => `smile ${day}`
const smileDays = days.map(addSmile);

//index 추가하기
const numDays = days.map((day,index) => `${index} ${day}`);

console.log(smileDays);

 

1.7 Array filter

-배열에서 원하는 것만 추출하기

 

const num = [2,3,4,5,6,7,8,10,20,30,5,40]

const biggerTen = numers.filter(number => number > 10);

console.log(biggerTen);

 

 

1.8 ForEach includes push

-foreach, push 등의 다양한 배열함수 공부

 

let posts = ["hi", "hello", "bye"];

if (posts.includes("hello")){
	posts.push("hello");
}

posts.forEach(post => console.log(post));

'일상 > React' 카테고리의 다른 글

React 공부 (with nico 4장)  (0) 2021.01.08
React 공부 (with nico 3장)  (0) 2021.01.07
React 공부 (with nico 2장)  (0) 2021.01.07
React 공부 (with reactjs.org 2)  (0) 2021.01.05
React 공부 (with reactjs.org)  (0) 2021.01.05

참고 : https://ko.reactjs.org/docs/handling-events.html

 

이벤트 처리하기 – React

A JavaScript library for building user interfaces

ko.reactjs.org

-Event 처리 bind 및 렌더링 관련 이야기라서 꼭 다시 이해하고, 콜백 이해하기

 


참고 : https://ko.reactjs.org/docs/conditional-rendering.html

 

조건부 렌더링 – React

A JavaScript library for building user interfaces

ko.reactjs.org

 

lass LoginControl extends React.Component {
  constructor(props) {
    super(props);
    this.handleLoginClick = this.handleLoginClick.bind(this);
    this.handleLogoutClick = this.handleLogoutClick.bind(this);
    this.state = {isLoggedIn: false};
  }

  handleLoginClick() {
    this.setState({isLoggedIn: true});
  }

  handleLogoutClick() {
    this.setState({isLoggedIn: false});
  }

  render() {
    const isLoggedIn = this.state.isLoggedIn;
    let button;
    if (isLoggedIn) {
      button = <LogoutButton onClick={this.handleLogoutClick} />;
    } else {
      button = <LoginButton onClick={this.handleLoginClick} />;
    }

    return (
      <div>
        <Greeting isLoggedIn={isLoggedIn} />
        {button}
      </div>
    );
  }
}

ReactDOM.render(
  <LoginControl />,
  document.getElementById('root')
);

-조건문을 이렇게 표현할 수 있음. 대부분 state를 사용하는듯

 

function Mailbox(props) {
  const unreadMessages = props.unreadMessages;
  return (
    <div>
      <h1>Hello!</h1>
      {unreadMessages.length > 0 &&
        <h2>
          You have {unreadMessages.length} unread messages.
        </h2>
      }
    </div>
  );
}

const messages = ['React', 'Re: React', 'Re:Re: React'];
ReactDOM.render(
  <Mailbox unreadMessages={messages} />,
  document.getElementById('root')
);

-논리연산을 통해 if문을 대체하는 방안도 있음

 

render() {
  const isLoggedIn = this.state.isLoggedIn;
  return (
    <div>
      {isLoggedIn
        ? <LogoutButton onClick={this.handleLogoutClick} />
        : <LoginButton onClick={this.handleLoginClick} />
      }
    </div>
  );
}

- 이렇게 조건연산식으로도 if else문 구현 가능

 

function WarningBanner(props) {
  if (!props.warn) {
    return null;
  }

  return (
    <div className="warning">
      Warning!
    </div>
  );
}

class Page extends React.Component {
  constructor(props) {
    super(props);
    this.state = {showWarning: true};
    this.handleToggleClick = this.handleToggleClick.bind(this);
  }

  handleToggleClick() {
    this.setState(state => ({
      showWarning: !state.showWarning
    }));
  }

  render() {
    return (
      <div>
        <WarningBanner warn={this.state.showWarning} />
        <button onClick={this.handleToggleClick}>
          {this.state.showWarning ? 'Hide' : 'Show'}
        </button>
      </div>
    );
  }
}

ReactDOM.render(
  <Page />,
  document.getElementById('root')
);

-이렇게 렌더링을 막는 방법도 생각해볼만함

 


참고 : https://ko.reactjs.org/docs/lists-and-keys.html

 

const numbers = [1, 2, 3, 4, 5];
const listItems = numbers.map((numbers) =>
  <li>{numbers}</li>
);

ReactDOM.render(
  <ul>{listItems}</ul>,
  document.getElementById('root')
);

-여러개 컴포넌트 렌더링하기

const numbers = [1, 2, 3, 4, 5];
const listItems = numbers.map((number) =>
  <li key={number.toString()}>
    {number}
  </li>
);

const todoItems = todos.map((todo, index) =>
  // Only do this if items have no stable IDs
  <li key={index}>
    {todo.text}
  </li>
);

- key를사용할때는 이렇게 사용함

 

function ListItem(props) {
  const value = props.value;
  return (
    // 틀렸습니다! 여기에는 key를 지정할 필요가 없습니다.
    <li key={value.toString()}>
      {value}
    </li>
  );
}

function NumberList(props) {
  const numbers = props.numbers;
  const listItems = numbers.map((number) =>
    // 틀렸습니다! 여기에 key를 지정해야 합니다.
    <ListItem value={number} />
  );
  return (
    <ul>
      {listItems}
    </ul>
  );
}

const numbers = [1, 2, 3, 4, 5];
ReactDOM.render(
  <NumberList numbers={numbers} />,
  document.getElementById('root')
);

function ListItem(props) {
  // 맞습니다! 여기에는 key를 지정할 필요가 없습니다.
  return <li>{props.value}</li>;
}

function NumberList(props) {
  const numbers = props.numbers;
  const listItems = numbers.map((number) =>
    // 맞습니다! 배열 안에 key를 지정해야 합니다.
    <ListItem key={number.toString()} value={number} />
  );
  return (
    <ul>
      {listItems}
    </ul>
  );
}

const numbers = [1, 2, 3, 4, 5];
ReactDOM.render(
  <NumberList numbers={numbers} />,
  document.getElementById('root')
);

- Key 지정 방법을 헷갈리면 안됨. 어디에 지정할지 잘 생각

'일상 > React' 카테고리의 다른 글

React 공부 (with nico 4장)  (0) 2021.01.08
React 공부 (with nico 3장)  (0) 2021.01.07
React 공부 (with nico 2장)  (0) 2021.01.07
React 공부 (with nico 1장)  (0) 2021.01.06
React 공부 (with reactjs.org)  (0) 2021.01.05

참고 페이지 : https://ko.reactjs.org/docs/introducing-jsx.html

 

JSX 소개 – React

A JavaScript library for building user interfaces

ko.reactjs.org

 

function formatName(user) {
  return user.firstName + ' ' + user.lastName;
}

const user = {
  firstName: 'Harper',
  lastName: 'Perez'
};

const element = (
  <h1>
    Hello, {formatName(user)}!
  </h1>
   <div>
    <h1>Hello!</h1>
    <h2>Good to see you here.</h2>
  </div>
);

ReactDOM.render(
  element,
  document.getElementById('root')
);

-변수 선언 방식이 매우 자유로움

 

- Hello, {formatName(user)} 이걸 봐서는 함수리턴값을 {}로 감싸서 문자열로 만드는듯

 

- <div> 안에 또 <h1> 넣어도 무방함

 

const element = <div tabIndex="0"></div>;

const element = <img src={user.avatarUrl}></img>;

- 블럭(div)안에 인자로 tabIndex=0이라는 값을 넣어준듯

 

- 원래 블럭의 인자값 src에 {user.avatarUrl} 처럼 변수를 넣을 수 도 있음

 


참고 : https://ko.reactjs.org/docs/components-and-props.html

 

Components and Props – React

A JavaScript library for building user interfaces

ko.reactjs.org

class Welcome extends React.Component {
  render() {
    return <h1>Hello, {this.props.name}</h1>;
  }
}

const element = <Welcome name="Sara" />;

-props는 객체인자를 받는 것임

 

-제일 밑에 줄 처럼 이제 컴포넌트를 블럭으로 받을 수 있음. 인자를 주면서

 

 

function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}

function App() {
  return (
    <div>
      <Welcome name="Sara" />
      <Welcome name="Cahal" />
      <Welcome name="Edite" />
    </div>
  );
}

ReactDOM.render(
  <App />,
  document.getElementById('root')
);

- 함수형태로 나타내면 이렇게 됨

 

class Clock extends React.Component {
  constructor(props) {
    super(props);
    this.state = {date: new Date()};
  }

  componentDidMount() {
    this.timerID = setInterval(
      () => this.tick(),
      1000
    );
  }

  componentWillUnmount() {
    clearInterval(this.timerID);
  }

  tick() {
    this.setState({
      date: new Date()
    });
  }

  render() {
    return (
      <div>
        <h1>Hello, world!</h1>
        <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
      </div>
    );
  }
}

ReactDOM.render(
  <Clock />,
  document.getElementById('root')
);

- 이렇게 하면 이제 clock은 함수가 아닌 클래스로 정의됨. 그냥 이자체로 시간을 계속 업데이트함

 

- 생성자 형식 잘 보기, 이제 제일 밑에 것 처럼 실행시키면 됨

 

-componentDidMount는 컴포넌트 출력물이 DOM에 렌더링 된 후에 실행

 

-componentWillUnmount는 이제 끝날때 실행

 

 

// Wrong
this.setState({
  counter: this.state.counter + this.props.increment,
});

// Correct
this.setState((state, props) => ({
  counter: state.counter + props.increment
}));

// Correct
this.setState(function(state, props) {
  return {
    counter: state.counter + props.increment
  };
});

-setState 사용 방법

 


참고 : https://ko.reactjs.org/docs/handling-events.html

 

이벤트 처리하기 – React

A JavaScript library for building user interfaces

ko.reactjs.org

 

function ActionLink() {
  function handleClick(e) {
    e.preventDefault();
    console.log('The link was clicked.');
  }

  return (
    <a href="#" onClick={handleClick}>
      Click me
    </a>
  );
}

-event 함수를 이렇게 할 수 도 있음

'일상 > React' 카테고리의 다른 글

React 공부 (with nico 4장)  (0) 2021.01.08
React 공부 (with nico 3장)  (0) 2021.01.07
React 공부 (with nico 2장)  (0) 2021.01.07
React 공부 (with nico 1장)  (0) 2021.01.06
React 공부 (with reactjs.org 2)  (0) 2021.01.05

+ Recent posts