如何使用 CSS 拉伸元素以適應瀏覽器視窗的整個高度?


要拉伸元素以適應 Web 瀏覽器視窗的整個高度,請使用高度屬性並將其設定為 100%。同等的高度:100% 也已設定為整個網頁。讓我們看看如何拉伸元素以適應瀏覽器視窗的整個高度。

設定容器

我們將設定 <div>。這將拉伸到 Web 瀏覽器視窗的整個高度和寬度 −

<div class="fullHeight">This div element will stretch to the whole height and width of the window</div>

HTML 文件的高度

使用高度屬性將網頁設定為高度 100% −

html, body {
   height: 100%;
   margin: 0;
}

容器的高度

容器 div 也設定為高度 100%。這是將被拉伸以適應整個視窗高度的元素,因為文件也設定為高度 100% −

.fullHeight{
   font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
   height: 100%;
   background: rgb(135, 27, 207);
   color:white;
   font-size: 40px;
   padding: 40px;
}

示例

要拉伸元素以使用 CSS 適應瀏覽器視窗的整個高度,程式碼如下 −

<!DOCTYPE html>
<html>
<head>
   <title>Page Title</title>
   <style>
      *{
         box-sizing: border-box;
      }
      html, body {
         height: 100%;
         margin: 0;
      }
      .fullHeight{
         font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
         height: 100%;
         background: rgb(135, 27, 207);
         color:white;
         font-size: 40px;
         padding: 40px;
      }
   </style>
</head>
<body>
   <div class="fullHeight">This div element will stretch to the whole height and width of the window</div>
</body>
</html>

更新於:2023 年 12 月 21 日

1K+ 瀏覽

開啟您的 職業

透過完成課程獲得認證

開始
廣告
© . All rights reserved.