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

PHPz
发布: 2023-09-07 16:17:02
转载
838人浏览过

如何使用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 中以居中对齐 -

有道小P
有道小P

有道小P,新一代AI全科学习助手,在学习中遇到任何问题都可以问我。

有道小P 64
查看详情 有道小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> 
登录后复制

示例

现在让我们看看使用 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中文网其它相关文章!

相关标签:
最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:tutorialspoint网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
热门推荐
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号