당신이 몰랐던 미디어 쿼리 하나! + 유사 검색어와의 비교

24094 단어 webdevcssmediaquery
요소 위로 마우스를 가져갈 수 있는 입력 장치가 사용자에게 있는지 알고 싶습니까? 호버링 장치가 없을 때 호버링 없이 호버링 상태를 표시하고 싶습니까? 마우스를 올리면 표시되는 요소를 보이지 않게 만들었지만 모바일 장치에서는 계속 표시되지 않습니까?

그거 알아? 이에 대한 CSS 전용 솔루션이 있습니다!

안녕하세요 여러분! 저는 인도 Uttarakhand에서 왔습니다. 저는 프론트 엔드 개발자, 학습자 및 개발자 블로거입니다.


.ltag__user__id__619020 .follow-action-button {
배경색: #6200ff !중요;
색상: #ffffff !중요;
테두리 색상: #6200ff !important;
}



고탐 티와리 팔로우



I'm a Front-end developer who likes to develop pixel-perfect components using only HTML and CSS or build a reusable component in React.js.



문제 이해



내 포트폴리오 웹사이트를 위한 카드 구성 요소를 만들었습니다(작업 중). 이미지가 표시되고 그 위에 텍스트 콘텐츠가 표시됩니다. 텍스트 내용에 불투명도를 0으로 지정했습니다. 이제 텍스트 내용은 사용자가 텍스트 위로 마우스를 가져가거나 초점을 맞출 때만 표시됩니다.

나는 모바일 사용자가 요소 위로 마우스를 가져갈 수 없기 때문에 UX가 좋지 않다는 것을 깨달을 때까지 그것을 해결했습니다.

이것에 대한 미디어 쿼리가 있어야 한다고 생각해서 구글링을 했고 WUOLAH! 이런 종류의 문제를 해결하기 위해 미디어 쿼리를 찾았고 유사한 미디어 쿼리를 세 개 더 찾았습니다(몇 번에 걸쳐 설명하겠습니다).

다음은 카드 구성요소의 HTML 코드입니다.

 <a
    rel="noopener noreferrer"
    target="_blank"
    href="https://bit.ly/35eecgK"
    class="recentlypublished__post"
>
    <img 
        src="https://bit.ly/2RUHcr6"
        alt="cover photo"
        class="recentlypublished__img"
    />
    <div class="recentlypublished__textbody">
        <p class="recentlypublished__date">May 30, 2021</p>
        <h3 class="recentlypublished__title">
            You are a developer just like me. No?
        </h3>
        <p class="recentlypublished__description">
            In the field of development, you will thrive if you keep
            learning, write good performing clean code, and stay away
            from...
        </p>
        <i
            class="
            fa fa-external-link-alt
            recentlypublished__externallinkicon
            "
        ></i>
    </div>
</a>


다음은 스타일 지정을 위한 CSS 코드이므로 무시해도 됩니다(미디어 쿼리 제외).

*,
*::before,
*::after {
  box-sizing: border-box;
}

body {
  margin: 2rem;
  line-height: 1.6;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto,
 Oxygen, Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif;
}

h1,
h2,
h3,
h4,
h5,
h6,
p {
  margin: 0;
}

img {
  display: block;
  width: 100%;
}

.recentlypublished__post {
  display: block;
  width: 100%;
  min-width: 200px;
  max-width: 600px;
  text-decoration: none;
  color: inherit;
  border-radius: 2rem;
  transition: box-shadow 200ms linear, transform 200ms ease-in-out;
  position: relative;
  color: #fefefe;
}

.recentlypublished__post:hover {
  transform: scale(1.05);
  box-shadow: 0 20px 40px -10px rgba(0, 0, 0, 0.5);
}

.recentlypublished__post:focus {
  outline: 0;
  transform: scale(1.05);
  box-shadow: 0 0px 0 10px rgba(0, 0, 0, 0.19);
}

.recentlypublished__textbody {
  position: absolute;
  top: 0rem;
  left: 0rem;
  padding: 2rem 1.5rem;
  width: 100%;
  height: 100%;
  opacity: 0;
  transition: opacity 80ms linear;
  z-index: -1;
}

.recentlypublished__textbody > * {
  transition: transform 250ms ease-out;
  transform: translateY(2rem);
  text-shadow: 2px 0px 15px #00331c;
}

.recentlypublished__textbody::before,
.recentlypublished__textbody::after {
  content: "";
  position: absolute;
  border-radius: 2rem;
  z-index: -1;
  left: 0;
  width: 100%;
  height: 100%;
}

.recentlypublished__img {
  border-radius: 2rem;
}

.recentlypublished__title, 
.recentlypublished__description {
  line-height: 1;
}

.recentlypublished__description {
  position: absolute;
  bottom: 10%;
  width: 90%;
}

.recentlypublished__externallinkicon {
  position: absolute;
  top: 0;
  right: 0;
  padding: 1rem;
}

.recentlypublished__post:hover > .recentlypublished__textbody,
.recentlypublished__post:focus > .recentlypublished__textbody {
  z-index: 2;
  opacity: 1;
}

.recentlypublished__post:hover > .recentlypublished__textbody::before,
.recentlypublished__post:focus > .recentlypublished__textbody::before {
  top: 0;
  background-image: linear-gradient(
    180deg, 
    #232323cf, 
    #202020bf 20%, 
    transparent 60%
  );
}

.recentlypublished__post:hover > .recentlypublished__textbody::after,
.recentlypublished__post:focus > .recentlypublished__textbody::after {
  bottom: 0;
  background-image: linear-gradient(
    0deg, 
    #232323cf, 
    #202020bf 20%, 
    transparent 60%
  );
}

.recentlypublished__post:hover > .recentlypublished__textbody > *,
.recentlypublished__post:focus > .recentlypublished__textbody > * {
  transform: translateY(0rem);
}


우리는 :hover:focus 상태에서 텍스트 콘텐츠를 표시하는 카드 구성 요소를 구축했습니다. 시원한!

다음은 :hover:focus 상태를 보여주는 미리 보기입니다.

하지만 모바일이나 태블릿에서는 어떻게 될까요?



대부분의 모바일 또는 태블릿에는 기본 터치 입력이 있으며 호버링을 지원하지 않습니다. 이러한 모바일 사용자의 경우 항상 다음과 같이 표시됩니다.



그것은 나쁜 UX입니다. 사용자는 해당 기사나 링크의 컨텍스트를 알 수 없습니다.

따라서 이제 사용자에게 호버링 장치가 없을 때마다 사용자에게 텍스트가 표시되도록 할 것입니다.

Note: Users can tap and hold the card to activate the hover state, but they have no idea about that invisible content.


마우스 오버 미디어 쿼리 소개


any-hover는 사용 가능한 입력 메커니즘이 사용자가 요소 위로 마우스를 가져가도록 허용하는지 확인하는 미디어 쿼리입니다.

호버링을 허용하는 경우 any-hover: hover가 적용됩니다.

호버링을 허용하지 않는 경우 any-hover: none가 적용됩니다.

마우스 오버 사용: 없음



이전 CSS 코드 끝에 이 코드를 추가하기만 하면 됩니다.

/* Just for a responsive behaviour */
@media (max-width: 460px) {
  .recentlypublished__date {
    font-size: calc(0.3rem + 2vw);
  }
  .recentlypublished__title {
    font-size: calc(0.38rem + 2vw);
  }
  .recentlypublished__description {
    font-size: calc(0.2rem + 2vw);
  }
}

/* Just for a responsive behaviour */
@media (max-width: 280px) {
  .recentlypublished__description {
    display: none;
  }
}

/* -----any-hover implementation----- */
/* if any input device does not have
hover capability then: */
@media (any-hover: none) {
  .recentlypublished__textbody {
    opacity: 1;
    z-index: 2;
  }
  .recentlypublished__textbody::before {
    top: 0;
    background-image: linear-gradient(
      180deg,
      #232323cf,
      #202020bf 20%,
      transparent 60%
    );
  }
  .recentlypublished__textbody::after {
    bottom: 0;
    background-image: linear-gradient(
      0deg,
      #232323cf,
      #202020bf 20%,
      transparent 60%
    );
  }
  .recentlypublished__date,
  .recentlypublished__title,
  .recentlypublished__description {
    transform: translateY(0rem);
  }
}



아래의 완성된 Codepen:



사용 가능한 입력 메커니즘 중 호버링을 지원하지 않는 것이 있는지 확인하기 위해 미디어 쿼리any-hover: none를 추가했습니다. 둘 다 사실입니다). 그런 다음 참인 경우 텍스트 콘텐츠를 표시합니다.

그게 다야!

Remember: In CSS, whatever comes later gets applied (if it has the same specificity). So, if you mess up with the order of media queries, you may get unexpected results.



보너스: 세 가지 유사한 쿼리 및 설명


any-hover: none : any-hover: hover와 같지만 기본 입력 메커니즘만 조회합니다.
hover: hover|none : 기본 입력 메커니즘(브라우저에서 제공)이 포인팅 장치입니까? 그렇다면 얼마나 정확합니까? (Coarse는 정확도가 제한된 포인팅 장치에 해당)
any-hover : pointer: fine|coarse|none와 동일하지만 모든 입력 장치를 테스트하고 쿼리를 만족하는 장치가 있으면 참입니다.

모든 것을 요약한 표




재산/상황
터치만
커서
터치 + 커서
커서 + 터치

any-pointer: fine|coarse|none없음
호버링
없음
호버링
pointer없음
호버링
호버링
호버링




hover조잡한
좋아
조잡한
좋아
any-hover조잡한
미세하고 거친
거친 & 미세
미세하고 거친


IE 및 Opera Mini용 아님



이러한 기능에 대해 이야기할 때 브라우저 지원은 매우 중요합니다.
2021년에는 상호 작용 미디어 기능(pointer이 포함됨)이 브라우저 간에 상당히 잘 지원됩니다.



결론



다음은 Patrick H. Lauke의 article that explains all this in more detail입니다. 문자 그대로 이러한 쿼리에 대해 더 알아야 하는 거의 모든 것을 다룹니다.

내 뉴스레터를 구독하고 매주 일요일 받은 편지함에서 이와 같은 기사를 직접 받아보세요.

Keep coding imperfectly. Keep coding experimentally.



읽어 주셔서 감사합니다. 나는 당신이 뭔가를 배웠기를 바랍니다.

좋은 웹페이지 즐겨찾기