HTML - style 屬性



HTML 的style 屬性包含 CSS 樣式宣告,用於將其應用於元素。

這是一個全域性屬性,建議在單獨的檔案中定義樣式。style 屬性和<style> 元素具有相同的目的,允許快速樣式設定。

如果在任何元素內部使用 style 屬性進行樣式設定,則可以將其稱為內聯 CSS。

語法

<element style="property:value;">

應用於

由於 style 是一個全域性屬性,它適用於所有元素,儘管它可能對某些元素沒有影響(放置在 head 元素內的標籤)。

HTML style 屬性示例

下面的示例將說明 HTML style 屬性,以及我們應該在哪裡以及如何使用此屬性!

使用 style 屬性進行內聯樣式設定

在下面的示例中,我們建立了兩個元素 h1 和 p,並對它們都應用了樣式。

<!DOCTYPE html>
<html lang="en">

<head>
   <title>HTML style attribute</title>
</head>

<body>
   <!-- Example of style attribute-->
   <h1>
       <span style="color: green;">Tutorials</span>point
   </h1>
   <p style="margin-top: -20px; margin-left: 100px">
       Simply Easy Learning
   </p>
</body>

</html>

使用 style 屬性覆蓋內部 CSS

內部 css 優先順序最高,如果我們在任何元素上應用 CSS 並使用 style 屬性更改該元素的樣式,它將優先考慮內聯 css。

<!DOCTYPE html>
<html lang="en">

<head>
   <title>HTML style attribute</title>
   <style>
       span{
           color: black;
       }
   </style>
</head>

<body>
   <!-- Example of style attribute-->
   <h1>
       <span style="color: green;">Tutorials</span>point
   </h1>
   <p style="margin-top: -20px; margin-left: 100px">
       Simply Easy Learning
   </p>
</body>

</html>

覆蓋 style 屬性值

正如您在前面的示例中看到的,內聯 CSS 是瀏覽器遵循的優先順序最高的 CSS。但是,如果我們使用 !important,例如 color: black !important;,那麼我們可以覆蓋 style 屬性值。

<!DOCTYPE html>
<html lang="en">

<head>
   <title>HTML style attribute</title>
   <style>
       span{
           color: black !important;
       }
   </style>
</head>

<body>
   <!-- Example of style attribute-->
   <h1>
       <span style="color: green;">Tutorials</span>point
   </h1>
   <p style="margin-top: -20px; margin-left: 100px">
       Simply Easy Learning
   </p>
</body>

</html>

支援的瀏覽器

屬性 Chrome Edge Firefox Safari Opera
style
html_attributes_reference.htm
廣告
© . All rights reserved.