CSS 용기 조회 - 응답식 웹 디자인의 미래가 다가온다

9747 단어 webdevcsshtml
스마트폰 사용자의 대량 증가와 이러한 장치의 기능이 끊임없이 강화됨에 따라 웹 응용 프로그램이 모든 화면 크기에서 정상적으로 작동할 수 있도록 하는 것이 그 어느 때보다 중요하다.다행히도, CSS는 여러 가지 방법을 제공하여, 서로 다른 장치에서 서로 다른 방식으로 같은 HTML에 스타일을 설정할 수 있다.

즉각적인 응답 웹 디자인


You can skip to the next section if you're already familiar with @media queries.


CSS에서 @media 조회를 사용할 수 있으며, 장치나 브라우저/사용자 에이전트 속성에 따라 조건부로 CSS 스타일을 적용할 수 있습니다.이러한 속성은 화면 너비, 장치 방향, 장치가 화면 판독기인지 프린터인지 등입니다.
다음은 매체가 어떻게 일을 하는지 조회하는 것을 보여 주는 작은 시범이다.
우리는 html에 하나만 추가하면 된다div.
<div class="box">
    This is a responsive box. Resize your browser width to see the styles change
<div>
다음은 Dell CSS입니다.
.box {
  background: lightblue;
  width:100%;
  height:100vh;
}

@media(max-width:800px) {
  .box {
    background: hotpink;
    color: white;
    font-weight: 700;
  }
}

여기에서 전체 데모를 볼 수 있습니다.
https://codepen.io/rajatkapoor/full/NWpgWor
만약 데스크톱/노트북에서 상술한 링크를 열면, 검은색 텍스트가 적힌 파란색 배경의 화면을 볼 수 있을 것이다.예를 들면 다음과 같습니다.

하지만 스마트폰에서 그것을 켜면 배경은 파란색이 아니라 분홍색이고 텍스트는 흰색으로 쓰일 것이다.

신기하죠?


이것은 가능합니다. 왜냐하면 @media 개의 조회가 있기 때문입니다.이것은 장치 화면의 폭이 800px보다 작을 때만 일부 스타일을 적용할 수 있기 때문이다.이것이 바로 휴대전화와 데스크톱 스타일이 다른 CSS다.
@media(max-width:800px) {
  .box {
    background: hotpink;
    color: white;
    font-weight: 700;
  }
}

@container 질의 입력


@container queries are only supported on Chrome Canary with the enable-container-queries flag enabled. You can download Chrome Canary here. Once installed, open the URL chrome://flags/#enable-container-queries and enable container queries.

There is a polyfill under development that you can use to use container queries today. You can check it out here.

@container 쿼리는 CSS의 다양한 기능 중 하나입니다.미디어 쿼리는 브라우저 속성(너비, 방향 등)에 따라서만 CSS 스타일을 조건부로 적용할 수 있고, 컨테이너 쿼리는 컨테이너의 속성에 따라 조건부로 스타일을 적용할 수 있습니다!
예를 들어 용기 조회를 사용하면 카드가 있는 요소의 크기에 따라 카드의 양식을 설정하여 다른 방식으로 표시할 수 있다.이것이 바로 우리가 열심히 건설할 것이다.

다음은 우리가 구축하고자 하는 내용이다


우리는 화면의 폭이 아니라 용기의 폭에 따라 스타일을 바꿀 카드를 만들 것이다.
Here's a demo that works only on Chrome canary.
Here's the same demo with the cqfill polyfill.
github repository 에서 이 프레젠테이션의 전체 코드를 볼 수 있습니다.

한번 해봅시다.


이 프로젝트에서 좋은 일반 HTML과 CSS를 사용할 것입니다.이것은 우리의 최초의 HTML이다.또한 "styles.css 파일"에 링크되어 있습니다.
<!-- index.html -->
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Container Queries | Rajat Kapoor</title>
    <!-- our own styles -->
    <link href="./styles.css" rel="stylesheet">
</head>

<body>
</body>

</html>
그림, 제목, 텍스트가 있는 아주 간단한 카드를 만들 것입니다.이 카드는 그림이 있는 card--header 카드와 제목과 다른 카드 내용이 있는 card--body 카드가 있을 것이다.카드의 스타일은 flexflex-direction: row이므로 이미지는 왼쪽에 있고 나머지 텍스트는 오른쪽에 있습니다.
우리는 이 카드를 div와 종류parent large로 포장하고 이 모든 것을 container로 포장하여 페이지의 모든 내용을 가운데에 놓을 것이다.
<!-- index.html  -->
<!-- ... -->

<body>
    <div class="container">
        <div class="parent large">
            <div class="card ">
                <div class="card--header ">
                    <img class="card--image" src="./img.jpeg" alt="card image">
                    <!-- we have this img.jpeg file in our folder -->
                </div>
                <div class="card--body ">
                    <h1 class="card--title ">
                        Lorem ipsum dolor sit amet.
                    </h1>
                    <h3 class="card--content ">
                        Lorem ipsum dolor, sit amet consectetur adipisicing elit. Nihil expedita accusantium, quidem
                        ducimus doloribus architecto a est deleniti, rerum saepe hic. Repellendus itaque ab officiis
                        voluptate ea earum perferendis consequatur!
                    </h3>
                </div>
            </div>
        </div>
    </div>

</body>

/* styles.css */
body {
    background-color: lightblue;
}

.container {
    display: grid;
    place-items: center;
    grid-gap: 1em;
}

.card {
    background: white;
    border-radius: 2em;
    display: flex;
    flex-direction: row;
    overflow: hidden;
    padding: 2em;
}

.card--header {
    width: 100%;
}

.card--image {
    border-radius: 1em;
    object-fit: cover;
    height: 100%;
    width: 100%;
}

.card--body {
    padding: 2em;
    flex: 3
}

.card--header {
    flex: 2
}

.large {
    width: 100%;
}

다음은 페이지의 모양입니다.

현재, 우리는 클래스 div 에 다른 parent small 를 추가하고, 같은 카드를 복사해서 붙일 것입니다.우리는 또한 small류에 대해 양식을 정의할 것이다.
<!-- index.html -->

<body>
    <div class="container">
        <div class="parent large">
            <div class="card">
               <!-- ...card -->
            </div>
        </div>
        <div class="parent small">
            <div class="card">
               <!-- ...card -->
            </div>
        </div>
    </div>

</body>

// styles.css

.small {
    width: 500px;
}    
이 두 장의 카드는 완전히 같습니다. 단지 두 개의 다른 div s에 있습니다. 그것들의 외관은 다음과 같습니다.

컨테이너 질의 추가


우리는 카드의 텍스트 내용이 용기의 폭이 500px보다 작지 않도록 그림 아래에 있기를 희망합니다.카드의 배경을 핫핑크로 바꾸고 텍스트를 흰색으로 바꾸어 더욱 뚜렷하게 변경할 것입니다.
컨테이너 쿼리가 작동하도록 컨테이너에 CSS를 추가하여 컨테이너 컨텍스트 - 컨테이너 컨텍스트의 하위 컨테이너 쿼리가 컨테이너의 속성에 반응하도록 정의해야 합니다.우리는 이 카드의 상하문을 포함하는 클래스div를 사용할 것이다.이를 위해 클래스 CSSparent를 수정합니다.
/* styles.css */

.parent {
    contain: layout inline-size style;
}

현재, 우리는 용기 조회를 카드에 추가할 수 있다.
/* styles.css */

@container(max-width: 500px) {
    .card {
        flex-direction: column;
        background-color: pink;
    }
}
이렇게!현재 브라우저로 돌아가면 parent 의 카드와 클래스 div 가 새로운 스타일을 적용한 것을 볼 수 있습니다.

예예🎉


우리는 장치 속성 (화면 크기) 뿐만 아니라 용기 크기에 따라 스타일을 제어할 수 있습니다.이것이 바로 용기 조회의 위력이다.

보너스. - 작은 거 크기 조절할 수 있게.


CSS를 추가하면 크기를 빠르게 조절할 수 있다는 것을 아십니까?우리는 우리의 parent반을 위해 이 일을 할 것이다.
/* styles.css */

.parent {
    contain: layout inline-size style;
    resize: horizontal;
    overflow: auto;
}
현재 두 개parentparent는 용기 조회가 정상적으로 작동하는지 확인하기 위해 크기를 수평으로 조정할 수 있습니다.

결론

div 조회를 통해 우리는 더욱 스마트한 방식으로 응답성 디자인을 처리할 수 있다.즉 container 조회는 개발의 초기 단계에 있다는 것이다.현재는 생산에서 이런 것들을 사용하는 것을 건의하지 않는다.사실, 내가 이 글을 쓰기 시작했을 때부터 이 글을 다 쓰기 시작했을 때까지, CSSWG는 문법을 바꾸었다😅.
웹 개발과 관련된 더 많은 내용을 얻습니다.

Special thanks to for helping me with debugging why my container queries were not working in Chrome Canary. You can also read more about container queries in this article

좋은 웹페이지 즐겨찾기