실무에서 익히게 된 각종 property의 사용법과 크고 작은 테크닉, 설정법 등을 별도로 백업할 필요가 있음을 느껴 Notion과 Velog에 정리한 내용을 백업한다. 이 카테고리 역시 수시로 백업하고, 어느 정도 분량이 쌓이게 되면 수시로 업로드 할 예정이다.
마찬가지로 이 게시글 역시 Notion의 통합 페이지에서 전체 내용을 확인할 수 있다.
Notion의 HTML & CSS 통합 페이지 바로 가기
var() - Mozilla
fallback - Mozilla
CSS Function var()는 그 어떤 여타 property 값의 일부를 대신하여 '사용자 정의 Property'('CSS Variable'로 불리기도 하는)의 값을 삽입할 수 있다. 또한 var() function은 property명, 선택자(selectors) 또는 그 어느 property 값들로는 사용될 수 없다고 MDN web docs는 설명하고 있다 .
The var() CSS function can be used to insert the value of a custom property (sometimes called a "CSS variable") instead of any part of a value of another property. The var() function cannot be used in property names, selectors or anything else besides property values. - MDN web docs
function의 첫 번째 인수로는 대체된 사용자 정의 property의 이름이 오며, 부차적인 두 번째 인수로는 fallback value*를
함수에 전달한다. 첫 번째 인수를 참조하는 사용자 정의 proeprty가 유효하지 않으면, 함수는 두 번째 값을 사용하게 된다.
The first argument to the function is the name of the custom property to be substituted. An optional second argument to the function serves as a fallback value. If the custom property referenced by the first argument is invalid, the function uses the second value.
var(<CUSTOM-PROPERTY-NAME>, <DECLARATION-VALUE>)
Note: 사용자 정의 properties와 같은, fallback 문법은 ,(comma)를 허용한다. 예를 들어, var(--foo, red, blue)
는 read, blue;를 fallback으로 정의한다. 이는, 첫 번째 ,(comma)와 function의 끝 사이의 어떤 것도 fallback 값으로 여겨진다는 것이다.
Note: The syntax of the fallback, like that of custom properties, allows commas. For example, var(--foo, red, blue) defines a fallback of red, blue; that is, anything between the first comma and the end of the function is considered a fallback value.
:root{ --main-bg-color: pink; } body{ background-color: var(--main-bg-color); }
.component .header{ color: var(--header-color, blue) /* header-color가 설정되지 않았으니 fallback value인 blue가 남는다. */ } /* --text-color로 세 번째 block에서 #080을 선언하였고, 이 것이 화면에 표시 불가능한 경우 대체값(fallback value)인 black이 도출된다. */ .component .text{ color: var(--text-color, black); } .component{ --text-color: #080; }
IE는 이 기능을 지원하지 않는다. (망할!)
fallback value
란?위의 내용을 해석하면 이러하다 :
fallback value
는 요청한 주요의 것(main thing)이 가능하지 않을 때 사용되는 값이다. CSS의 font-family를 생각해 보자. 사용자를 위해 시도하는 폰트가 불가능한 경우를 대비한 fallback 폰트를 항상 제공해야 한다.
이는 요컨대, font-family: 'Noto Sans KR', sans-serif;
와 같은 것을 말한다. 예를 들어 google font에서 Noto Sans KR을 import 한 후, 개체에 이를 적용하려 할 때 특정 플랫폼 등에서 적용되지 않는 경우를 대비해서 san-serif나 serif등의 폰트를 두 번째 optional 값으로 추가 작성하는 경우를 생각해보자. 바로 이해할 수 있다.
반드시 정해진 규격에 맞게 이미지를 보여줘야 할 때, 또한 그 source 파일의 이미지 규격이 항상 동일하지 않는 경우는 필연적으로 규격에 맞게 이미지를 cropping 해야 하는 경우가 발생한다. 이러한 상황에서 이미지의 본래 가로 세로 비율에 맞게(with aspect ratio) 조절할 것인지, 비율에 맞지 않게 조절할 것인지는 웹 디자이너의 선택에 따르게 된다. 일반적인 경우 그 비율을 맞추는 것이 요구되며, 이러한 경우 object-fit
을 사용하면 아주 간편하게 이미지를 cropping 할 수 있다. 이 object-fit
CSS property는 그 container에 맞게 resize 해야 할 <img>
<video>
와 같은, 재 배치할 구성 요소의 본문을 설정한다.
The object-fit CSS property sets how the content of a replaced element, such as an <img>
or <video>
, should be resized to fit its container. -MDN web docs
object-fit
property는 다음의 값 리스트에서 하나의 키워드로 특정된다.
The object-fit property is specified as a single keyword chosen from the list of values below.
contain
재 배치된 본문은 구성 요소의 content-box 내에 꼭 맞을 때까지 본 비율을 유지하며 scale된다. 객체 전체는 그의 본 비율로 유지되도록 box에 맞게 만들어지므로 그의 본 비율이 box의 비율과 맞지 않는다면 'letterboxed(공백이 포함된 박스 내에 비율을 유지한 객체가 담긴 형태)'된다.
*The replaced content is scaled to maintain its aspect ratio while fitting within the element’s content box. The entire object is made to fill the box, while preserving its aspect ratio, so the object will be "letterboxed" if its aspect ratio does not match the aspect ratio of the box.*
cover*
재 배치된 본문은 구성 요소의 본문 box 전체를 채울 때까지 그의 본 비율을 유지하도록 sizing된다. 객체의 본 비율이 box의 본 비율과 맞지 않으면 객체는 clipping(잘려나감)된다.
*The replaced content is sized to maintain its aspect ratio while filling the element’s entire content box. If the object's aspect ratio does not match the aspect ratio of its box, then the object will be clipped to fit.*
fill
재 배치된 본문은 구성 요소의 box를 채우도록 sizing된다. 객체 전체는 완전하게 box를 채우게 된다. 객체의 본 비율이 그 box의 본 비율과 맞지 않는 경우 객체는 stretched(늘려짐)된다.
*The replaced content is sized to fill the element’s content box. The entire object will completely fill the box. If the object's aspect ratio does not match the aspect ratio of its box, then the object will be stretched to fit.*
none
재 배치된 본문은 sizing되지 않는다.
The replaced content is not resized.
scale-down
본문이 none
또는 contain
으로 특정해 sizing된다면, 어느 쪽이든 실체의 객체 사이즈보다 작게 도출한다.
*The content is sized as if none or contain were specified, whichever would result in a smaller concrete object size.*
Example : HTML
<section> <h2>object-fit: fill</h2> <img class="fill" src="https://mdn.mozillademos.org/files/6457/mdn_logo_only_color.png" alt="MDN Logo"> <img class="fill narrow" src="https://mdn.mozillademos.org/files/6457/mdn_logo_only_color.png" alt="MDN Logo"> <h2>object-fit: contain</h2> <img class="contain" src="https://mdn.mozillademos.org/files/6457/mdn_logo_only_color.png" alt="MDN Logo"> <img class="contain narrow" src="https://mdn.mozillademos.org/files/6457/mdn_logo_only_color.png" alt="MDN Logo"> <h2>object-fit: cover</h2> <img class="cover" src="https://mdn.mozillademos.org/files/6457/mdn_logo_only_color.png" alt="MDN Logo" <img class="cover narrow" src="https://mdn.mozillademos.org/files/6457/mdn_logo_only_color.png" alt="MDN Logo"> <h2>object-fit: none</h2> <img class="none" src="https://mdn.mozillademos.org/files/6457/mdn_logo_only_color.png" alt="MDN Logo"> <img class="none narrow" src="https://mdn.mozillademos.org/files/6457/mdn_logo_only_color.png" alt="MDN Logo"> <h2>object-fit: scale-down</h2> <img class="scale-down" src="https://mdn.mozillademos.org/files/6457/mdn_logo_only_color.png" alt="MDN Logo"> <img class="scale-down narrow" src="https://mdn.mozillademos.org/files/6457/mdn_logo_only_color.png" alt="MDN Logo"> </section> ```
Example : CSS
h2 { font-family: Courier New, monospace; font-size: 1em; margin: 1em 0 0.3em; } div { display: flex; flex-direction: column; flex-wrap: wrap; align-items: flex-start; height: 940px; } img { width: 150px; height: 100px; border: 1px solid #000; margin: 10px 0; } .narrow { width: 100px; height: 150px; } .fill { object-fit: fill; } .contain { object-fit: contain; } .cover { object-fit: cover; } .none { object-fit: none; } .scale-down { object-fit: scale-down; } ```
Result
(당연히) IE에는 호환되지 않는다.
How to disable a link using only CSS?
pointer-events - Mozilla
링크 연결을 위한 경우가 아니더라도, 편의 상 <a href="">
를 사용한 작업이 필요하나 동시에 링크 기능이 필요치 않은 경우는 생각보다 자주 만나볼 수 있다. (손 쉽게 image slider를 구현하기 위해서 같은) 물론, 별도의 페이지 링크가 필요하지 않은 경우 <a href="#">
하는 경우가 널리 알려져 있지만, 이 때 해당 태그로 연결된 링크를 클릭하는 경우 페이지의 최 상단으로 이동하게 되기 때문에 이 방법은 본질적으로 무용하다. 이러한 경우에 가장 쉽고 빠르게, CSS property만을 사용하여 링크 기능을 disable하는 방법에 대해 소개한다.
간단하다. 대입할 요소의 선택자에 pointer-events: none;
css property를 대입하면 끝이다!
더불어 cursor: default;
까지 더 해주면 해당 요소에 cursor를 올렸을 때 클릭이 유도되는 사용자의 반응을 사전에 방지할 수 있어 더욱 좋다.
Example : CSS
.not-active{ pointer-events: none; cursor: default; }
Example : HTML
<a href="httpsnot-active://stackoverflow.com" class="not-active">Link</a>
이 property는 IE도 지원한다! 와 맙소사!
How to maintain responsive image aspect ratio?
padding-bottom - Mozilla
정해진 규격에서 div를 반응형 width와 height을 가지도록 구성하는 것은 쉽다. 하지만 반응형으로 재 배치해야 하는 대상이 이미지인 경우, 그 것도 해당 이미지의 정해진 비율을 유지하면서, 각기 다른 사이즈의 이미지 파일들을 소스로 갖는 경우에는 직관적인 방법이 쉽게 떠오르지 않는다. 반응형 이미지로 구성하는 것 자체는 쉬워도 이미지의 위 아래에 위치한 타 요소들과의 간격을 일정히 유지하며 container box의 여백을 남기지 않기란 단순 가로 세로 수치의 조정만으로는 어렵기 때문이다.
이 문제를 해결하면서 생각치도 못 했던 방법을 만났다.
바로 positioning과 padding
을 활용한 이미지 비율의 조정이다.
position: relative;
자식인 내부 요소는 position: absolute;
해 준다.height: 0;
으로 설정한다.width: 100%;
, height: 100%;
해 준다. CSS
// Method 1. .image-wrapper{ height: 0; position: relative; padding-bottom: 52.63%; } .image-wrapper .image{ height: 100%; width: 100%; position: absolute; } // Method 2. .outer-wrapper{ height: 0; padding-top: 125%; position: relative; overflow: hidden; } .inner-wrapper{ width: 100%; height: 100%; position: absolute; overflow: hidden; }
HTML
// Method 1. <div class="image-wrapper"> <div class="image"></div> </div> // Method 2. <div className="slider-wrapper"> <div className="inner-wrapper"> <input type="radio" name="slide" id="Slide1" className="control" defaultChecked/> <label htmlFor="Slide1" id="sl1"></label> <div className="overflow-wrapper"> <a href="{void(0)}" className="slide"><img src="https://cdn-dev.image_path.png" alt="Failed to load Image"/></a> </div> </div> </div>
RESULT
position: absolute;
, position: relative;
, padding
을 활용한 테크닉이므로
IE에서도 정상 작동 된다.
position - Mozilla
Difference between position:sticky and position:fixed?
Fixed Header는 스크롤 진행도에 상관없이 항상' 지정 위치에 '고정되어' 스크롤을 내리던 올리던 늘 화면에 노출되는 Header를 말하며, Sticky Button은 화면을 스크롤해도 viewport 내에서 요소가 지나쳐가지 않고, 스크롤을 '따라다니는' 버튼이다. 이는 웹 사이트의 레이아웃을 정할 때 항상 기본으로 깔고 가는 기본 중의 기본이기도 하다.
Fixed Header
display: flex;
display: flex;
하는 경우, 이 가로와 세로 길이를 가지고 하나의 container를 생성하여 효과적인 수직 또는 수평 구조로 구성할 수 있게 한다. 이 때, header의 내부에 위치한 item들을 통해 레이아웃을 분리하지 않는다면, header는 하나의 요소를 container로 갖게 된다. 요컨대, 한 줄(row)을 통째로 사용하는 container로 구성하겠다는 의미가 된다.position: fixed;
top: 0;
, width: 100%;
top: 0;
으로 설정하며, 플랫폼 및 디바이스의 종류와 상관없이 상단 너비 전체를 차지 시킬 것이므로 width: 100%;
로 설정해 준다.justify-content: center;
align-items: center;
text-align: center;
z-index: 10;
Sticky Button
position: sticky;
z-index: 10;
bottom: 0px;
HTML
// Fixed-Header <div className="outermost"> <div className="header"> <img src="https://cdn-dev.logo-path.png" alt="Failed to load Image" className="img-title-logo"/> </div> //Sticky-Button <div className="wrapper"> <div className="container"> <div className="order-btn-wrapper"> <div className="order-btn" id="order-btn">주문하기</div> </div> </div> </div> </div> </div> ```
CSS
// FIXED-HEADER .header{ top: 0; width: 100%; margin: 0; height: 56px; background-color: #ffffff; border: 1px solid #e0e0e0; display: flex; justify-content: center; align-items: center; position: fixed; z-index: 12; text-align: center; } .img-title-logo{ width: 120px; height: 15px; padding: 0 0 0 2px; object-fit: contain; } // STICKY-BUTTON .order-btn-wrapper{ width: 100%; margin: 0 auto; min-width: 360px; width: 100%; max-width: 510px; height: 64px; background-color: #1c1c1e; text-align: center; z-index: 11; position: sticky; bottom: 0px; left: 0px; top: calc(100% - 64px); } .order-btn{ width: calc(100% - 40px); margin: 0px 20px 17px 20px; height: 29px; color: white; font-size: 20px; font-family: 'Noto Sans KR', sans-serif; font-weight: bold; line-height: 1.45; letter-spacing: 1px; padding-top: 18px; } ```
RESULT
position: fixed;
는 IE에서도 지원하나, position: sticky;
는 지원하지 않는다.
calc()
는 CSS property 값을 특정할 때 계산을 행할 수 있게 한다. 이는 <length>
, <frequency>
, <angle>
, <time>
, <percentage>
어디에나 사용될 수 있으며, <number>
또는 <integer>
가 허용된다.
The calc() CSS function lets you perform calculations when specifying CSS property values. It can be used anywhere a <length>
, <frequency>
, <angle>
, <time>
, <percentage>
, <number>
, or <integer>
is allowed. -MDN
property: calc(expression);
의 형식으로, width: calc(100% - 80px);
과 같이 선언하면 된다. 참고로 expression(표현식) 영역에 들어갈 수식으로는 +(Addition), -(Subtraction), *(Multiplication), /(Division)이 대입 될 수 있으며, Division의 right-hand, 즉 우항인 divider는 반드시 number로 작성하여야 한다. 표현식의 operands(피 연산자)는 어느 <length>
문법의 값도 될 것이다. 표현식 내에서의 각 값으로 다른 단위를 사용할 수 있으며, 원한다면 필요한 연산 순서를 확립하기 위해 대괄호()도 사용할 수 있다.
*+
Addition.-
Subtraction.*
Multiplication. At least one of the arguments must be a [<number>](https://developer.mozilla.org/en-US/docs/Web/CSS/number)
./
Division. The right-hand side must be a [<number>](https://developer.mozilla.org/en-US/docs/Web/CSS/number)
.*
The operands in the expression may be any [<length>](https://developer.mozilla.org/en-US/docs/Web/CSS/length)
syntax value. You can use different units for each value in your expression, if you wish. You may also use parentheses to establish computation order when needed.
.component{ width: calc(100% - 40px); }
IE에서는 호환이 되지 않는다.