如何使用 div 標籤設定 HTML 元素的樣式?
<div> 標籤用作 HTML 元素的容器。藉助此標籤,我們可以輕鬆定義 HTML 文件的一部分。它也用於將大型 HTML 元素部分組合在一起並輕鬆格式化它們。<div> 標籤與塊級元素一起使用。
<div> 標籤接受所有 CSS 屬性,並使用 class 和 id 等屬性設定其中的元素樣式。
語法
以下是 <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>
廣告