REM과 PX의 관계: 더 접근하기 쉬운 미디어 쿼리를 작성하는 방법

PHPz
풀어 주다: 2024-08-27 18:01:11
원래의
732명이 탐색했습니다.

우리는 개발자입니다. 우리는 가장 반응성이 뛰어난 레이아웃을 개발하고 싶습니다. 우리는 다양한 장치, 해상도 및 사용자 설정을 수용하고 싶습니다. 우리는 모든 스타일시트에서 일관된 단위를 사용하고 싶습니다. 우리는 가능한 한 적은 양의 수학을 하고 싶습니다.

언제 이걸 원하나요? 지금!
우리는 무엇을 알아야 합니까? 정말 많아요!
어떻게 해야 할까요? 맞춤형 SASS 기능으로!

SASS 기능을 사용하면 시스템 및 브라우저 수준 설정을 이해하고 고려하여 더 많은 사용자를 수용할 수 있습니다. rem 값이 픽셀 값과 어떻게 관련되는지, 그리고 이들 사이의 관계에 어떤 영향을 미칠 수 있는지 살펴보겠습니다. 1rem은 거의 항상 16px로 시작하지만 사용자가 이를 변경할 수 있는 방법이 있습니다. 나중에 작성하게 될 이 SASS 함수는 대규모 프로젝트에 적용할 수 있고 기존 프로젝트에 점진적으로 도입할 수 있기 때문에 매우 유용합니다.

배경

제가 이 주제를 조사하게 된 계기는 There's No Such Thing as a Desktop Screen이라는 기사였습니다. Hajime Yamasaki Vukelic은 반응형 디자인에 대해 "반응성은 단순히 임의의 화면 너비 집합에 관한 것이 아닙니다..."라고 말했습니다. 반응성은 견고성에 관한 것입니다. 페이지가 무너지기 전에 페이지를 얼마나 늘리거나 짤 수 있는지 말입니다.” 하지메는 그의 아버지가 기본적으로 400% 정규 규모로 웹을 탐색하는 방법에 대해 이야기합니다. 이것이 극단적인 경우처럼 보일 수 있지만 사용자가 디스플레이 크기를 조정할 수 있는 다양한 방법과 우리가 작성하는 스타일이 이러한 설정 변경에 의해 어떻게 영향을 받는지 아는 것이 중요합니다.

스케일링된 디스플레이

픽셀이 무엇인지 정확히 이해하면서 최대한 작은 것부터 시작해 보겠습니다. 개발자에 관한 한 픽셀에는 두 가지 유형이 있습니다. 주어진 화면의 빛 점의 양인 장치 픽셀과 측정 단위인 CSS 픽셀이 있습니다. 장치 픽셀은 일반적으로 CSS 픽셀과 동일하지 않습니다. 어떤 설정이 각 값에 영향을 미치는지 파악할 수 있도록 둘 사이의 차이점을 이해하는 것이 중요합니다.

하지메의 아버지처럼 사용자가 화면의 콘텐츠 크기를 변경할 수 있는 방법에는 여러 가지가 있습니다. 사용자가 디스플레이 크기를 조정할 수 있는 가장 일반적인 방법:

  • 디스플레이 해상도 변경(시스템 설정)
  • 브라우저 탭 확대(Mac에서는 ⌘ 및 +, Windows에서는 Ctrl 및 + 누르기)
  • 브라우저 설정에서 글꼴 크기를 늘립니다.

디스플레이 해상도를 변경하고 브라우저에서 확대/축소하는 첫 번째와 두 번째 옵션은 기본적으로 동일한 작업을 수행합니다. 두 방법 모두 CSS 픽셀의 크기를 조정하여 각 CSS 픽셀이 더 많은 장치 픽셀을 차지하도록 합니다. 이 경우 레이아웃은 모두 비례적으로 확장됩니다. 1rem은 여전히 ​​16px과 같지만 각 CSS 픽셀은 더 많은 장치 픽셀을 차지합니다. 이를 테스트하려면 "모바일" 레이아웃이 실행될 때까지 브라우저 탭을 확대하면 됩니다. 이 설정은 테스트가 빠르며 일반적으로 큰 문제를 일으키지 않습니다.

브라우저 글꼴 크기를 변경하면 가장 큰 변화가 발생합니다. 기본적으로 브라우저 설정은 "medium"이며 이는 Chrome에서 1rem이 16px임을 의미합니다. 사용자가 글꼴 크기를 늘리면 1rem 값은 증가하지만 다른 값은 확장되지 않습니다. 1rem은 더 많은 CSS 픽셀과 같으므로 더 많은 장치 픽셀을 차지합니다. Chrome에서는 글꼴 크기를 "매우 크게"로 설정하면 1rem은 24px와 같습니다. CSS 픽셀의 크기는 동일하게 유지되며 변경된 것은 루트 글꼴 크기입니다. 루트 글꼴 크기를 참조하는 모든 값이 영향을 받습니다.

The REM to PX relation: how to write more accessible media queries

코드에 픽셀 값과 rem 값이 혼합되어 있으면 rem 값의 크기는 조정되지만 픽셀 값은 동일하게 유지되므로 레이아웃 문제가 발생할 수 있습니다. 위 이미지는 텍스트가 rem 값으로 설정되고 최대 너비, 열 너비 및 패딩이 픽셀 값으로 설정될 때 레이아웃이 얼마나 크게 변경될 수 있는지에 대한 간단한 예를 보여줍니다. 반응형 레이아웃은 루트 글꼴 크기에 따라 크기가 조정되어야 합니다.

미디어 쿼리의 문제

일반적으로 미디어 쿼리를 작성하는 방법은 다음과 같습니다.

@media (min-width: 1000px) {
    ...declarations here
}
로그인 후 복사

우리는 모든 사용자 설정에 반응하고 적응할 수 있도록 노력하고 있으므로 가능한 모든 곳에서 상대 단위를 사용하고 싶습니다. 미디어 쿼리에서 픽셀 대신 rem 값을 사용해 보겠습니다.

@media (min-width: 62.5rem) {
    ...declarations here
}
로그인 후 복사

기본 브라우저 설정에서 1000px는 62.5rem과 같습니다
1rem = 16px
1000px / 16px/rem = 62.5rem
이는 상대 단위를 작성하고 싶을 때마다 수행해야 하는 수학처럼 보입니다. 우리는 처음부터 수학을 할 필요가 없다고 말했습니다.

1rem = 10px로 만드는 일반적인 수정 사항이 있습니다. 이는 일반적으로 프로젝트의 상용구를 설정하는 동안 수행됩니다. html 선택기를 대상으로 하여 루트 요소의 루트 글꼴 크기를 덮어씁니다.

html {
    font-size: 62.5% 
    // this is math 
    // but it only needs to be done once for the whole project 
    // so I'll let it slide
}
로그인 후 복사

Now any time we want to convert a pixel value from the design to a rem value in our code we just have to carry the decimal one place.
1rem = 10px
To get a value of 1000px, we use 100rem. This still involves math but is fairly minor.

Now, when using a rem value, we can safely assume that 1rem will be 10px.
Right?
Yes?
Example?
No need. We know it is true. We have used rem for widths, heights, paddings, margins, translates or any other declaration without any issue. But…will there be any issue using it in the condition for a media query?

@media (min-width: 100rem) {
    // does is trigger at 1000px as expected?
    ...declarations here
}
로그인 후 복사


Open the example in a new window and play with the width of the viewport. When the “desktop” media query triggers then the background will turn blue.

What is happening?

The values for a media query are calculated before any other rules are set, so the ruleset we applied to the html element in the start of our project will not be applied in the condition of the media query. According to this media query, 1rem is still equal to 16px. We expected 100rem to be 1000px but it ended up being 1600px.

If you change the browser font size to “very large” and refresh the example, you will notice that 1rem = 15px and the 100rem media query won’t trigger until 2400px. If your monitor isn’t wide enough to see that change happen, zoom out on the browser with ⌘/Ctrl and + .

The condition for the media query is not scaling consistently with the browser’s desired font size.

  • Font size “Medium”:
    • 1rem = 10px
    • Media query: 100rem = 1600px
    • rem to px ratio: 0.0625
  • Font size “Very Large”:
    • 1rem = 15px
    • Media query: 100rem = 2400px
    • rem to px ratio: 0.0416666667

For content and layouts to scale consistently, we need the rem to px ratio to always remain the same.

REMPX()

This has taken a long time to get to even suggesting a solution to a problem that we maybe didn’t know we had.

Let’s create a custom SASS function that will allow us to write our code in pixel values and be rendered as rem values. I came across this function on a legacy project at work but I believe it was heavily inspired by this quick article: Convert pixel values to rem, Sass style, by Bhargav Shah. Since this article was written, CSS introduced its own rem() function which calculates the remainder of a fraction so instead we’ll name our function rempx().

$html-font-size: 16px;

@function stripUnit($value) {
    @return $value / ($value * 0 + 1);
}

@function rempx($pxValue) {
    @return #{stripUnit($pxValue) / stripUnit($html-font-size)}rem;
}

//implementation:
.image {
  height: rempx(300px);
}
로그인 후 복사


Open the example in a new window and play with the width of the viewport and change the browser font size (refresh the page after you update the font size).

Notice how after we change the browser font size to “very large” (after a page a refresh), the 1rem square becomes larger and you can see that 1rem is equal to 24px.

When used in the condition of a media query, a rempx value will scale accordingly with the browsers font size. With the font size set to “very large”, the desktop layout rempx(1000px) will trigger at the viewport width of 1500px. The scaling of the content and layout behave the same way as when we zoom in on the browser.

A huge benefit of writing all your units with the rempx() function is you can write pixel values from the designs and then it renders it as a rem value in the browser. This function is very easy to introduce to a project or include in the boilerplate of your future projects.

Wrapping up

This function can be written once and used everywhere.
We can take the pixel values from the design and generate a scalable rem value.
Our media query triggers relative to the root font size.
All our layout and content scales consistently.
No math necessary.
Better user experience across a wider range of user settings.
Better user existence overall.
Better developer existence overall.
This function improves our existence.

Further reading

There’s No Such Thing as a Desktop Screen Hajime Yamasaki Vukelic

Zoom, zoom, and zoom: the three types of browser (and CSS!) magnification, Miriam Suzanne

Convert pixel values to rem, Sass style, Bhargav Shah

위 내용은 REM과 PX의 관계: 더 접근하기 쉬운 미디어 쿼리를 작성하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:dev.to
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!