要使用 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元素?的詳細內容,更多請關注www.92cms.cn其它相關文章!






