CSS3 實現16:9大屏居中顯示

显示昵称已被使用#發表於2024-03-29

大屏專案中,一般需要在不同解析度上顯示居中顯示大屏內容,且不出現捲軸。實際展示大屏的硬體裝置比例不一,為了相容,並且不出現UI被拉伸的情況,發現可以使用CSS3的transfrom-scale屬性,並配合CSS變數實現。
其中transfrom-scale用在大屏繪製最外層盒子上,盒子內的樣式按照UI給出的16:9的比例繪製。
效果圖:

程式碼展示最外層盒子的縮放樣式及比例計算:
style

<style>
  :root {
    --transformScale: 1;
    --positionWidth: 1920px;
    --positionHeight: 1080px;
  }

  * {
    margin: 0;
    padding: 0;
  }

  .container {
    display: flex;
    align-items: center;
    justify-content: center;
    overflow: hidden;
    height: 100vh;
    width: 100vw;
  }

  .position {
    width: var(--positionWidth);
    height: var(--positionHeight);
  }

  .box {
    height: 1080px;
    width: 1920px;
    background-color: aquamarine;
    transform: scale(var(--transformScale));
    transform-origin: 0% 0%;
  }
</style>

html

<!-- 為了獲取螢幕寬高新增的元素 -->
<div class="container">
  <!-- 為了定位新增的元素 -->
  <div class="position">
    <div class="box"></div>
  </div>
</div>

script

<script>
  // 全域性縮放比基礎寬
  const width = 1920;
  // 全域性縮放比基礎高
  const height = 1080;
  // 寬高比
  const ratio = 16 / 9;

  const getBaseScale = () => {
    const element = document.getElementsByClassName("container")[0];
    // 獲取可視區域的寬度
    const w = element.clientWidth;
    // 獲取可視區域的高
    const h = element.clientHeight;
    // 根據寬高計算比例
    let s = 1;
    if (w / h >= ratio) {
      // 裝置左右留白 以高度為基礎計算縮放比
      s = h / height;
    } else {
      s = w / width;
    }

    const pw = s * 1920 + "px";
    const ph = s * 1080 + "px";

    // 賦值
    document
      .getElementsByTagName("body")[0]
      .style.setProperty("--transformScale", s);
    document
      .getElementsByTagName("body")[0]
      .style.setProperty("--positionWidth", pw);
    document
      .getElementsByTagName("body")[0]
      .style.setProperty("--positionHeight", ph);
  };

  // 視窗變化
  onresize = getBaseScale;

  // 載入
  onload = getBaseScale;
</script>

相關文章