如何使用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>
執行以上程式碼後,它將生成一個輸出,顯示網頁上居中的文字。
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP