본문 바로가기
개발공부/HTML&CSS

[CSS] margin 값 넣는 방식 분류

by 안스토리 2023. 1. 29.

CSS 속성 중에 margin에 값을 넣는 방식이 처음에는 헷갈렸다.

 

/* Apply to all four sides */
margin: 1em;
margin: -3px;

/* top and bottom | left and right */
margin: 5% auto;

/* top | left and right | bottom */
margin: 1em auto 2em;

/* top | right | bottom | left */
margin: 2px 1em 0 auto;

 

margin 문법 설명에는 위와 같은 예시가 있는데, 무슨 말인가 했다.

이제 명확히 알았다. 간단한 건데 익숙해지기 까지는 시간이 걸렸다.

 

case 1) 값을 1개만 명시한 경우

해당 값은 top(상), right(우), bottom(하), left(좌) 전체에 적용된다.

/* Apply to all four sides */
margin: 1em;
margin: -3px;

 

case 2) 값을 2개만 명시한 경우

첫번째 값은 top(상), bottom(하)에 적용되고,

두 번째 값은 left(좌), right(우)에 적용된다.

/* top and bottom | left and right */
margin: 5% auto;

 

case 3) 값을 3개만 명시한 경우

첫번째 값은 top(상)에 적용되고,

두 번째 값은 left(좌), right(우)에 적용되고,

세 번째 값을 bottom(하)에 적용된다.

/* top | left and right | bottom */
margin: 1em auto 2em;

 

case 4) 값을 4개 모두 명시한 경우

첫번째 값은 top(상)에 적용되고,

두 번째 값은 right(우)에 적용되고,

세 번째 값은 bottom(하)에 적용되고,

네 번째 값은 left(좌)에 적용된다.

※시계방향

/* top | right | bottom | left */
margin: 2px 1em 0 auto;

 

 

| 참고 자료

 

https://developer.mozilla.org/en-US/docs/Web/CSS/margin

 

margin - CSS: Cascading Style Sheets | MDN

The margin CSS shorthand property sets the margin area on all four sides of an element.

developer.mozilla.org