如何使用CSS居中<div>标签?


对于网页布局,使用CSS居中<div>至关重要。几乎每个开发者在其职业生涯中都会遇到居中div的任务,如果不是每天的话。每个人都有自己方便的方法,但这偶尔会让初学者感到恼火。

这些CSS方法提高了网页设计的视觉吸引力和可用性,保证了动态和流畅的居中效果。在了解这些方法之前,让我们快速了解一下div标签。

HTML div标签

在HTML中,<div>标签用作分隔符或部分。HTML <div>标签用于分组HTML元素,这些元素随后被赋予容器并赋予CSS或JavaScript样式。class或id属性使得装饰div标签变得简单。

语法

以下是HTML div标签的语法:

<div>......</div>

示例

让我们来看下面的例子,我们将使用flexbox居中div。

<!DOCTYPE html>
<html>
<head>
   <style>
      .tp {
         height: 300px;
         background: #D5F5E3;
         display: flex;
         align-items: center;
         color: #DE3163;
         font-family: verdana;
         justify-content: center;
      }
      .tp1 {
         background-color: #CCD1D1;
         width: 150px;
         height: 50px;
      }
   </style>
</head>
<body>
   <div class="tp">
      <div class="tp1">WELCOME TO TUTORIALSPOINT</div>
   </div>
</body>
</html>

运行以上代码后,它将生成一个包含div框的输出,其中一个居中显示在网页上。

示例

考虑另一种情况,我们将使用CSS Justify-Content属性

<!DOCTYPE html>
<html>
<head>
   <style>
      body {
         background-color: #D5F5E3;
      }
      .tp {
         margin: 100px;
         border: 1px solid #17202A;
         display: flex;
         justify-content: center;
         font-family: verdana;
         color: #DE3163;
      }
   </style>
</head>
<body>
   <div class="tp">
      <p>MS Dhoni Lifts The WorldCup</p>
   </div>
</body>
</html>

运行以上代码后,输出窗口将弹出,显示网页上居中的div文本。

示例

在下面的例子中,我们将使用grid居中div。

<!DOCTYPE html>
<html>
<head>
   <style>
      body {
         background-color: #E8DAEF;
      }
      section {
         font-family: verdana;
         color: #DE3163;
         font-size: 50px;
         height: 450px;
         display: grid;
         place-items: center;
      }
      .tp {
         background-color: yellow;
      }
   </style>
</head>
<body>
   <section>
      <div class="tp">WELCOME</div>
   </section>
</body>
</html>

运行以上代码后,它将生成一个输出,显示网页上居中的文本。

更新于:2024年1月8日

浏览量:299

开启你的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.