首頁  >  文章  >  web前端  >  如何使用CSS在所有瀏覽器中垂直居中一個div元素?

如何使用CSS在所有瀏覽器中垂直居中一個div元素?

PHPz
PHPz轉載
2023-09-07 16:17:02596瀏覽

如何使用CSS在所有瀏覽器中垂直居中一個div元素?

要使用 CSS 在所有瀏覽器中垂直居中 div 元素,請使用 Flexbox。 CSS3提供了另一個版面模式Flexible Box,俗稱Flexbox。使用此模式,您可以輕鬆地為複雜的應用程式和網頁建立佈局。與浮動不同,Flexbox 佈局可以完全控制框的方向、對齊方式、順序和大小。

標籤是 HTML 中元素的容器。我們可以在 div 中放置任何類型的內容。首先新增元素,然後使用 CSS 設定它們的樣式。我們現在只能將 div 垂直居中,但可以水平居中。

為了讓 div 垂直居中,我們將使用 flex 屬性,align-items 屬性。該值設定為 center 以使 div 居中。在下面的範例中,我們使用具有中心值的align-items屬性將其中一個div設定為居中對齊 -

demo2 {
   display: flex;
   align-items: center;
   height: 60%;
} 

然後將內容設定在同一個 div demo2 中以居中對齊 -

<div class="demo2">
   <img src="https://www.tutorialspoint.com/archery/images/archery-mini-logo.jpg" alt="Archery Tutorial">
   <p>Archery is a bow and arrow game where each player is supposed to shoot arrows from a bow and hit a fixed target.</p>
</div> 

範例

現在讓我們看看使用 CSS 為所有瀏覽器垂直居中 div 元素的範例 -

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <meta http-equiv="X-UA-Compatible" content="IE=edge">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <title>Center Div Elements</title>
</head>
<style>
   body,
   html {
      height: 100%;
   }
   .demo2 {
      display: flex;
      align-items: center;
      height: 60%;
   }
   .demo1,
   .demo2 {
      border: 2px solid skyblue;
      background-color: blue;
      color: white;
   }
</style>
<body>
   <h1>Archery Tutorial</h1>
   <div class="demo1">
      <img src="https://www.tutorialspoint.com/archery/images/archery-mini-logo.jpg"
      alt="Archery Tutorial">
      <p>Archery is a bow and arrow game where each player is supposed to shoot arrows from a
      bow and hit a fixed target.</p>
   </div>
   <p>Let us now center the div elements: </p>
   <div class="demo2">
      <img src="https://www.tutorialspoint.com/archery/images/archery-mini-logo.jpg"
      alt="Archery Tutorial">
      <p>Archery is a bow and arrow game where each player is supposed to shoot arrows from a
      bow and hit a fixed target.</p>
   </div>
</body>
</html>

以上是如何使用CSS在所有瀏覽器中垂直居中一個div元素?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除