如何使用 div 標籤設定 HTML 元素的樣式
?


<div> 標籤用作 HTML 元素的容器。藉助此標籤,我們可以輕鬆定義 HTML 文件的一部分。它還用於將 HTML 元素的大塊內容組合在一起並輕鬆格式化它們。<div> 標籤與塊級元素一起使用。

<div> 標籤接受所有 CSS 屬性,並使用 classid 等屬性對其內部的元素進行樣式設定。

語法

<div> 標籤的語法如下。

<div class='division'>Content…</div>

示例 1

下面是一個在 HTML 中為 div 標籤新增樣式的示例。

<!DOCTYPE html> <html> <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"> <style> .parent { border: 1rem solid green; margin: 1rem; padding: 1rem 1rem; text-align: center; box-shadow: 2px 2px 20px 23px aquamarine; } .division { display: inline-block; border: 1px solid aquamarine; padding: 1rem 1rem; background-color: #2ecc71; color: white; } </style> </head> <body> <div class='parent'> <div class='division'>div tag 1</div> <div class='division'>div tag 2</div> <div class='division'>div tag 3</div> </div> </body> </html>

以下是上述示例程式的輸出。

我們可以為 <div> 標籤新增更多樣式。

示例 2

下面是另一個在 HTML 中為 div 標籤新增樣式的示例。

<!DOCTYPE html> <html> <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"> <style> .parent { border: 1rem solid green; margin: 1rem; padding: 1rem 1rem; text-align: center; box-shadow: 2px 2px 20px 23px aquamarine; } .division { display: inline-block; border: 1px solid aquamarine; padding: 1rem 1rem; background-color: #2ecc71; color: white; text-transform: uppercase; text-decoration: underline; font-family: cursive; font-size: 1.2rem; font-weight: bolder; font-style: italic; } </style> </head> <body> <div class='parent'> <div class='division'>div tag 1</div> <div class='division'>div tag 2</div> <div class='division'>div tag 3</div> </div> </body> </html>

以下是上述示例程式的輸出。

示例 3

您可以嘗試執行以下程式碼,以使用 <div> 標籤為 HTML 元素設定樣式。新增的樣式規則將應用於 id 為“content”的元素。此處 id 是 CSS 選擇器。

<!DOCTYPE html> <html> <head> <style> #container p { line-height: 15px; margin: 20px; padding-bottom: 15px; text-align: justify; width: 130px; color: blue; } </style> <title>HTML div Tag</title> <link rel = "stylesheet" href = "style.css"> </head> <body> <div id = "container"> <p>Welcome to our website. We provide tutorials on various subjects.</p> </div> </body> </html>

更新於: 2022年10月19日

479 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

立即開始
廣告

© . All rights reserved.