본문 바로가기
LEARN/HTML | CSS

[HTML] selector 선택자 (tag, class, id) + style

by 아이엠제니 2022. 12. 28.

💾 Editor: VSCode


👉 기존 html 코드

    <div
        style="display:block; margin-left:auto; margin-right:auto; width: 400px; background-color: gold; padding: 10px;">
        <img src="main.jpg" style="width:100px; display:block; margin-left:auto; margin-right:auto;">
        <h3 style="text-align:center;">devje</h3>
        <p style="text-align:center;"><strong style="color:red;">Front-end</strong> Developer</p>
        <p style="text-align:center;">I want my dream to come true. The future is <strong
                style="color:blue">mine</strong>.</p>
    </div>

기존 html 코드에서 style 속성으로 넣었던 것을 모두 style.css 로 옮긴다.

html 파일 안에 html과 css를 연결하는 link 태그를 head 안에 작성한다.

 


👉 index.html => style.css (스타일 속성 옮기기)

  • index.html
<img src="main.jpg" class="profile">
  • style.css
.profile {
width:100px;
display:block;
margin-left:auto;
margin-right:auto;
}

img 태그에 class 속성 추가

style.css 파일에 코드 옮기기

 

html 태그에 style 속성을 넣었을 때와 style.css에 작성했을 때와의 차이는 없다.

다만 css로 관리하면 추후에 같은 class 속성을 사용하는 태그의 경우 코드 수정이 쉽다.

 


👉 수정본

  • index.html
    <div class="wrap">
        <img src="main.jpg" class="profile">
        <h3 class="title">devje</h3>
        <p id="special"><strong class="first-line">Front-end</strong> Developer</p>
        <p>I want my dream to come true. The future is <strong class="second-line">mine</strong>.</p>
    </div>

모든  style 속성을 제거

  • style.css
.wrap {
    display: block;
    margin-left: auto;
    margin-right: auto;
    width: 400px;
    background-color: gold;
    padding: 10px;
}

.profile {
    width: 100px;
    display: block;
    margin-left: auto;
    margin-right: auto;
}

.title,
#special,
p {
    text-align: center;
}

.first-line {
    color: red;
}

.second-line {
    color: blue;
}

👉 CSS

  • 스타일 보관 상자

 

👉 css 선택자 (selector)

  • html에 style 속성을 넣기보다는 css 파일로 관리하는 게 좋음
  • css를 사용할 때는 id 선택자보다는 class 선택자로 사용함
  • css 파일을 만든 후에는 html 파일에 link 태그 넣어야 함
    • 연결 안 하면 css 작동 안 함 (진짜 진짜 초보일 때 많이 하는 실수)

 

👉 선택자 우선순위

  • id > class > tag
    • id보다는 태그 안의 style 속성이 우선순위가 더 높음
  • style > id > class > tag

 

 

 

코딩애플 공부 기록
300x250

'LEARN > HTML | CSS' 카테고리의 다른 글

[CSS] layout 레이아웃 1 - float  (1) 2022.12.30
[HTML] div 박스 css design (box-shadow)  (0) 2022.12.29
[HTML] STYLING 웹페이지 스타일링  (0) 2022.12.26
[HTML] tag 태그  (0) 2022.12.25
[부스트코스] 8 미디어 쿼리  (0) 2022.03.22