如何使用 CSS 将 div 元素在所有浏览器中垂直居中?


要使用 CSSdiv 元素 在所有 浏览器 中垂直居中,可以使用 FlexboxCSS3 提供了另一种布局模式弹性盒,通常称为 Flexbox。使用此模式,您可以轻松创建复杂应用程序和网页的布局。与浮动不同,Flexbox 布局可以完全控制盒子的方向、对齐方式、顺序和大小。

<div> 标签是 HTML 中元素的容器。我们可以在 div 中放置任何类型的內容。首先添加元素,然后使用 CSS 对其进行样式设置。我们现在只能垂直居中 div,但也可以水平居中。

要垂直居中 div,我们将使用 flex 属性和 align-items 属性。将值设置为 center 以将 div 居中。在下面的示例中,我们已将其中一个 div 设置为使用 align-items 属性(值为 center)进行居中对齐 -

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

然后在相同的 div demo2 中设置内容以进行居中对齐 -

<div class="demo2"> <img src="https://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 元素在所有浏览器中垂直居中的示例 -

Open Compiler
<!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://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://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>

更新于: 2023-11-21

867 次浏览

启动你的 职业生涯

通过完成课程获得认证

开始学习
广告