HTML & CSS 실무(1): var, object-fit, disable a link, responsive layouts, Positioning (last update: 2020.12.17.)

devpark·2020년 12월 17일
0

HTML & CSS

목록 보기
1/2

3. CSS & Styling

Introduction


실무에서 익히게 된 각종 property의 사용법과 크고 작은 테크닉, 설정법 등을 별도로 백업할 필요가 있음을 느껴 Notion과 Velog에 정리한 내용을 백업한다. 이 카테고리 역시 수시로 백업하고, 어느 정도 분량이 쌓이게 되면 수시로 업로드 할 예정이다.


마찬가지로 이 게시글 역시 Notion의 통합 페이지에서 전체 내용을 확인할 수 있다.
Notion의 HTML & CSS 통합 페이지 바로 가기


3-1. var in css : using variables in css style sheet

0. References

var() - Mozilla
fallback - Mozilla

1. Introduction


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

2. Syntax

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.

3. Examples

  • Using a custom property set on :root
:root{
	--main-bg-color: pink;
}
body{
	background-color: var(--main-bg-color);
}
  • Custom properties with fallbacks for use when the property has not been set
.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;
}

4. Browse Compatibility

IE는 이 기능을 지원하지 않는다. (망할!)

5. Remark : fallback value

  • 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 값으로 추가 작성하는 경우를 생각해보자. 바로 이해할 수 있다.


3-2. object-fit : cropping image with aspect ratio

0. References

object-fit - Mozilla

1. Introduction


반드시 정해진 규격에 맞게 이미지를 보여줘야 할 때, 또한 그 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

2. Syntax

object-fit property는 다음의 값 리스트에서 하나의 키워드로 특정된다.
The object-fit property is specified as a single keyword chosen from the list of values below.

  • Values
  1. 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.*

  2. 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.*

  3. 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.*

  4. none
    재 배치된 본문은 sizing되지 않는다.
    The replaced content is not resized.

  5. 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.*

3. Examples

  • 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

4. Browser Compatibility

(당연히) IE에는 호환되지 않는다.


0. References

How to disable a link using only CSS?
pointer-events - Mozilla

1. Introduction


링크 연결을 위한 경우가 아니더라도, 편의 상 <a href="">를 사용한 작업이 필요하나 동시에 링크 기능이 필요치 않은 경우는 생각보다 자주 만나볼 수 있다. (손 쉽게 image slider를 구현하기 위해서 같은) 물론, 별도의 페이지 링크가 필요하지 않은 경우 <a href="#">하는 경우가 널리 알려져 있지만, 이 때 해당 태그로 연결된 링크를 클릭하는 경우 페이지의 최 상단으로 이동하게 되기 때문에 이 방법은 본질적으로 무용하다. 이러한 경우에 가장 쉽고 빠르게, CSS property만을 사용하여 링크 기능을 disable하는 방법에 대해 소개한다.

2. Syntax

간단하다. 대입할 요소의 선택자에 pointer-events: none; css property를 대입하면 끝이다!
더불어 cursor: default;까지 더 해주면 해당 요소에 cursor를 올렸을 때 클릭이 유도되는 사용자의 반응을 사전에 방지할 수 있어 더욱 좋다.

3. Examples

Example : CSS

.not-active{
	pointer-events: none;
	cursor: default;
}

Example : HTML

<a href="httpsnot-active://stackoverflow.com" class="not-active">Link</a> 

4. Browser Compatibility

이 property는 IE도 지원한다! 와 맙소사!


3-4. responsive image resize with padding

0. References

How to maintain responsive image aspect ratio?
padding-bottom - Mozilla

1. Introduction


정해진 규격에서 div를 반응형 width와 height을 가지도록 구성하는 것은 쉽다. 하지만 반응형으로 재 배치해야 하는 대상이 이미지인 경우, 그 것도 해당 이미지의 정해진 비율을 유지하면서, 각기 다른 사이즈의 이미지 파일들을 소스로 갖는 경우에는 직관적인 방법이 쉽게 떠오르지 않는다. 반응형 이미지로 구성하는 것 자체는 쉬워도 이미지의 위 아래에 위치한 타 요소들과의 간격을 일정히 유지하며 container box의 여백을 남기지 않기란 단순 가로 세로 수치의 조정만으로는 어렵기 때문이다.

이 문제를 해결하면서 생각치도 못 했던 방법을 만났다.
바로 positioning과 padding을 활용한 이미지 비율의 조정이다.

2. Syntax

  1. container요소는 position: relative; 자식인 내부 요소는 position: absolute; 해 준다.
  2. 원하는 크기로, 이미지의 width를 height으로 나누어 비율로 만든다. (e.g. 3:4 → 125%)
  3. container 요소에 해당 비율을 padding-top 또는 padding-bottom의 값으로 대입한다.
  4. container 요소의 세로를 height: 0;으로 설정한다.
  5. 자식 요소를 width: 100%;, height: 100%; 해 준다.

3. Examples

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

4. Browser Compatibility

position: absolute;, position: relative;, padding을 활용한 테크닉이므로
IE에서도 정상 작동 된다.


3-5. Fixed Header, Sticky Button

0. References

position - Mozilla
Difference between position:sticky and position:fixed?

1. Introduction


Fixed Header는 스크롤 진행도에 상관없이 항상' 지정 위치에 '고정되어' 스크롤을 내리던 올리던 늘 화면에 노출되는 Header를 말하며, Sticky Button은 화면을 스크롤해도 viewport 내에서 요소가 지나쳐가지 않고, 스크롤을 '따라다니는' 버튼이다. 이는 웹 사이트의 레이아웃을 정할 때 항상 기본으로 깔고 가는 기본 중의 기본이기도 하다.

2. Syntax

Fixed Header

  1. display: flex;
    width와 height을 설정하고 display: flex;하는 경우, 이 가로와 세로 길이를 가지고 하나의 container를 생성하여 효과적인 수직 또는 수평 구조로 구성할 수 있게 한다. 이 때, header의 내부에 위치한 item들을 통해 레이아웃을 분리하지 않는다면, header는 하나의 요소를 container로 갖게 된다. 요컨대, 한 줄(row)을 통째로 사용하는 container로 구성하겠다는 의미가 된다.
  2. position: fixed;
    가장 핵심적인 property다. 요소를 특정 위치에 '고정'시킨다. 이 때의 '고정'이란, 스크롤 진행도와 상관없이 viewport 내 정해진 위치에 항상 요소를 고정한 상태로 노출 시킨다는 것이다. 쉽게 말 해, 스크롤을 내리든 올리든 항상 상단에 노출되는 사이트의 로고와 헤더, nav-bar등을 상상하면 쉽다.
  3. top: 0;, width: 100%;
    구성할 fixed-header는 항상 최 상단에 위치 시키고, 고정할 것이므로 top: 0;으로 설정하며, 플랫폼 및 디바이스의 종류와 상관없이 상단 너비 전체를 차지 시킬 것이므로 width: 100%;로 설정해 준다.
  4. justify-content: center; align-items: center; text-align: center;
    작성한 헤더 내부에 로고 등을 중앙 정렬하여 배치하는 경우에는 위의 코드들을 통해 내부 요소들을 중앙 정렬하도록 미리 설정해 줄 수 있다.
  5. z-index: 10;
    이제 작성한 헤더에 z-index를 1이상으로 올려두어, 스크롤에 따라 다른 요소들 위로 헤더가 '올라갈 수 있게' 한다. 즉 이 z-index 설정을 통해 다른 요소들보다 더 위의 우선 순위를 가지게 되며, 헤더가 여 타 요소에 가려져 노출되지 않는 문제를 방지할 수 있다.

Sticky Button

  1. position: sticky;
    viewport에 '붙어있도록' 설정한다. 이 property를 통해 구현한 버튼이 스크롤 여부와 상관없이 항상 사용자의 화면을 따라다닐 수 있게 된다.
  2. z-index: 10;
    마찬가지로 스크롤에 따라 다른 요소들이 화면에 노출되더라도, 그 요소들보다 높은 우선 순위를 부여함으로써 위로 구현한 버튼이 올라올 수 있도록 설정한다.
  3. bottom: 0px;
    구현한 sticky 버튼이 항상 화면의 최 하단에 붙어있도록 화면을 구성하려면 bottom: 0 property를 부여하여 최 하단에 요소를 배치한다.
    단, Sticky Button을 구현할 때는 해당 요소를 '담고 있는' 부모 요소의 크기에 주의하여야 한다. 스크롤 시 화면을 항상 따라다니는 버튼으로 구성하나 특정 스크롤 시점에서 멈추고, 더 이상 따라오지 않기를 바란다면 버튼을 담고 있는 container가 height을 멈출 시점까지의 길이를 갖도록 구성해야 하기 때문이다. 예를 들어, 버튼을 담고 있는 container의 height이 페이지 전체의 100%인 경우, 해당 요소는 스크롤이 끝날 때까지 화면을 따라다닐 것이며 중간에 멈추지 않는다. 따라서, container 요소의 분리와 수직적 재배치를 통해 해당 버튼이 따라갈 경로를 중간에 끊어줘야 한다!

3. Examples

  • 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

4. Browser Compatibility

position: fixed;는 IE에서도 지원하나, position: sticky;는 지원하지 않는다.


3-6. calc : the easiest way to set responsive width

0. References

calc() - Mozilla

1. Introduction


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

2. Syntax

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.

3. Examples

.component{
	width: calc(100% - 40px);
}

4. Browser Compatibility

IE에서는 호환이 되지 않는다.


profile
아! 응응애에요!

0개의 댓글