programing

주소 표시줄 표시 시 100vh 높이 - Chrome Mobile

codeshow 2023. 8. 15. 11:49
반응형

주소 표시줄 표시 시 100vh 높이 - Chrome Mobile

저는 이 문제를 몇 번 접했고 이 문제에 대한 해결책이 있는지 궁금했습니다.제 문제는 크롬 모바일 앱에서 발생합니다.거기서 조금 아래로 스크롤하면 주소 표시줄이 사라집니다. 지까지다, 좋니습금. 예를 들어 보겠습니다.
의 컨너의이테.height으로 설정됨100vh.

How it looks with the address bar

보시는 것처럼 밑부분이 잘립니다.

아래로 스크롤하면 다음과 같습니다.

enter image description here

이제는 좋아 보입니다.따라서 Chrome은 주소 표시줄의 높이를 뷰포트 높이로 계산합니다.그래서 제 질문은:

주소 표시줄이 있든 없든 똑같이 보이는 방법이 있습니까?그래서 용기가 팽창하거나 뭐 그런 거?

크롬 웹의 이 공식 기사에 따르면, 보이는 뷰포트를 채울 수 있는 높이를 설정하는 적절한 방법은 다음과 같습니다.height: 100%어느쪽든의 어느 에.<html>position: fixed원의소 되어 있듯이,.이 문서에서 설명하는 것처럼 이는 모바일 Safari와의 호환성을 보장하며 URL 표시줄의 크기와 관계가 없습니다.

사용해 보십시오.min-height: -webkit-fill-available에 추가할 수도 있습니다.height: 100vh

커뮤니티는 여전히 브라우저가 개발자의 관점에서 상단, 하단 및 측면 패널을 이동할 때 어떻게 행동해야 하는지에 대해 엄격한 동의를 얻지 못하고 있습니다.

질문에 언급된 문제는 잘 알려져 있습니다.

enter image description here

  1. 이 모든 것은 Apple Webkit 문제에서 시작되었습니다.문제 중 하나는 웹사이트 개발자들이 사용한 것입니다.vh글꼴 크기 계산을 위해(ppm(100/vh * 무엇인가)). 때로 글꼴 크기가 왜곡되어 CPU 것도 없고 환경이 됩니다.100vh는 CPU/GPU를 많이 사용하는 작업입니다.
    애플의 결정은 (주소 표시줄이 없는) 화면의 더 큰 크기를 100vh와 지속적으로 일치시키는 것이었습니다.주소 표시줄이 표시되고 사용자가100vh하단 부분이 화면 밖으로 나가는 높이입니다.많은 개발자들은 이 결정에 동의하지 않으며 뷰포트 단위가 동적이며 보이는 "뷰포트"와 정확히 같다고 생각합니다.

  2. Google Chrome 은 Apple 브라우저와 호환되며 동일한 결정을 고수하기로 결정했습니다.

  3. height: 100%실제 보이는 부분과 동일한 대부분의 최신 브라우저에서, 즉 높이는 스크롤하는 동안 주소 표시줄을 볼 수 있는지 또는 숨길 수 있는지에 따라 달라집니다.

  4. 화면 상단뿐만 아니라 하단(현대식 iOS)에도 막대가 나타날 수 있으며, 온스크린 키보드를 사용하면 보기가 짧아질 수 있습니다.모바일 장치에서 실제 크기를 확인할 수 있는 좋은 데모가 있습니다.100vh vs 100%.
    enter image description here


솔루션 1

html, body { height: 100%; }
.footer-element { 
  position: fixed; 
  bottom: 10px;
}

2솔션루 2
에 대한 어느 정도의 의존성을 보상합니다.vh가시적인 막대 높이가 "100vh - 100%"와 같다면 막대가 숨겨져 있을 때 차이는 0이 됩니다.

html, body { height: 100vh; }
.footer-element { 
  position: fixed; 
  bottom: calc(10px + (100vh - 100%));
}
.my-element {
  height: 100vh; /* Fallback for browsers that do not support Custom Properties */
  height: calc(var(--vh, 1vh) * 100);
}

이제 JavaScript에서 뷰포트의 내부 높이를 알아보겠습니다.

// First we get the viewport height and we multiple it by 1% to get a value for a vh unit
let vh = window.innerHeight * 0.01;
// Then we set the value in the --vh custom property to the root of the document
document.documentElement.style.setProperty('--vh', `${vh}px`);

출처: https://css-tricks.com/the-trick-to-viewport-units-on-mobile/

높이 설정으로 주소 표시줄 문제를 해결할 수 있습니다. html 및 body 태그에서 100%, 코스 밖에서 body의 여백과 패딩을 0으로 설정하고 더 나은 제어를 위해 메인 div에서 스크롤을 처리할 수도 있습니다.

뷰포트에 따라 다음과 같은 세 가지 장치가 새로 추가되었습니다.
sv* 뷰포트 주소 표시줄이 는 다음과 같습니다.
lv* 큰 또는 입니다.
dv*동적 뷰포트 크기(주소 표시줄에 따라 변경됨

사용.

주소 표시줄의 표시 여부에 따라 컨테이너의 크기가 변경되기를 원하기 때문에 원하는 단위는dvh.

.container {
    height: 100dvh;
}

이것이 도움이 되었기를 바랍니다!

진일보한 내용

유사한 문제가 발생하여 이 솔루션을 React와 함께 사용했습니다.JS:

import { useLayoutEffect, useState } from 'react';

function useWindowSize() {
  const [size, setSize] = useState([0, 0]);
  useLayoutEffect(() => {
    function updateSize() {
      setSize([window.innerWidth, window.innerHeight]);
    }
    window.addEventListener('resize', updateSize);
    updateSize();
    return () => window.removeEventListener('resize', updateSize);
  }, []);
  return size;
}

것이.useWindowSize기능은 React를 사용하여 브라우저 크기 조정의 Render 보기에서 가져옵니다.

코드에 사용했을 때 다음과 같이 표시되었습니다.

const MessageList = () => {
  const { messages } = useContext(ChatContext);
  const [, windowHeight] = useWindowSize();
  return (
    <div
      className="messages"
      style={{
        height: windowHeight - 80 - 48, // window - message form - navbar
      }}
    >
      {messages.map((m, i, list) => ( <Message ... /> )}
    </div>
  );
};

화면 탐색기와 브라우저 상단 표시줄이 있는 안드로이드 홈 버튼 없는 스마트폰이 높이에 포함되지 않도록 요소의 크기를 조정하는 방법을 방금 알아냈습니다.콘텐츠가 화면보다 크면 요소가 모든 것에 맞는 크기로 커져야 하기 때문에 최소 높이를 사용하고 있습니다.


편집:

JS에서 스타일 변경 대신 클래스를 사용하여 스니펫 추가

// save old window size to adjust only if width changed
let oldWidth = window.innerWidth,
  oldHeight = window.innerHeight;
// element to adjust
const target = document.querySelector(".vh100");
// adjust the size if window was resized
window.addEventListener("resize", handleResize);

function handleResize(initial = false) { // the parameter is used for calling the function on page load
  /*
   * if the width changed then resize
   * without this Chrome mobile resizes every time navbar is hidden
   */
  if (window.innerWidth !== oldWidth || initial) {
    // stretch the target
    target.classList.add("setting-100vh");
    // save height and apply as min height
    const h = target.clientHeight;
    target.classList.remove("setting-100vh");
    target.style.minHeight = h + "px";
  }
}
// call when page is loaded
handleResize(true);
* {
  margin: 0;
}

.vh100 {
  background-color: green;
}


/*
* Stretch the element to window borders and save the height in JS
*/

.setting-100vh {
  position: fixed;
  top: 0;
  bottom: 0;
  min-height: unset;
}
<body>
  <header class="vh100">
    <h1>100vh on mobile</h1>
  </header>
  <main>
    <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Possimus ipsa officia mollitia facilis esse cupiditate, nisi recusandae quas id enim alias eaque suscipit voluptates laudantium quasi saepe deserunt labore fuga deleniti placeat, necessitatibus
      quibusdam. Quaerat adipisci provident minima laboriosam modi ullam accusamus error dolores iure ducimus laborum similique distinctio temporibus voluptas nulla quod ipsa, nostrum quam cumque id animi unde consectetur incidunt! Dolorem sed quisquam
      at cumque. Cumque non nam exercitationem corporis? Minus sed explicabo maiores ipsam ratione. Quam, fugit asperiores nesciunt dolores culpa, numquam blanditiis sint dolorum ex corrupti illo veniam nostrum odio voluptatibus accusantium ullam impedit
      eligendi voluptates?</p>
  </main>
</body>

동적 보기 높이(dvh) 사용 시도(예: 100dvh) 비교적 새로운 속성이며 일부 브라우저에서는 여전히 지원하지 않을 수 있지만 주소 표시줄 문제를 해결합니다.

https://dev.to/frehner/css-vh-dvh-lvh-svh-and-vw-units-27k4

여기서 가장 중요한 답변을 조금 더 설명해 드리려고 합니다. 위에서 언급한 로스 라이트가 당신이 사용하기를 원한다는 것을 발견했습니다.height: 100%웹 브라우저의 주소 표시줄을 설명합니다.와 body 나, 이것작이 html 태그태러문본높그다합니다음같이과야이설해정를의와동면하려▁set▁the▁to▁for▁height▁however합▁equal다▁tag▁set니▁have,▁to▁for▁tag그러▁body▁the▁and▁you▁to▁work와 동일하게 설정해야 합니다.height: 100%그렇지 않으면 div가 제대로 확장되지 않습니다.

<!DOCTYPE html>
<html>
  <head>

    <style>

      html, body {
        height: 100%;
      }

      .fillViewport {
        height: 100%;
      }

      .redBackground {
        background-color: red;
      }

    </style>

  </head>
  <body>

    <div class="fillViewport redBackground"></div>

  <body>
</html>

다음 스니펫은 저에게 효과가 있었습니다.저는 포장지의 예로 메인 태그에 테두리를 삽입했습니다.

* {
  margin: 0;
  border: 0;
  padding: 0;
  box-sizing: border-box;
}

html {
  position: fixed;
  padding: 0.5rem;
  height: 100%;
  width: 100%;
}

body {
  position: relative;
  height: 100%;
  width: 100%;
}

main {
  position: relative;
  border: 1px solid black;
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
}

언급URL : https://stackoverflow.com/questions/52848856/100vh-height-when-address-bar-is-shown-chrome-mobile

반응형