In coding there are often many different solutions to a given problem. This is especially true when it comes to styling an HTML element.
在編碼中,對于給定問題通常有許多不同的解決方案。 在樣式化HTML元素時,尤其如此。
One of the easiest things to change is the color of text. But sometimes it seems like nothing you try is working:
更改顏色最容易的事情之一。 但是有時似乎您嘗試的任何方法都沒有起作用:
<style>h2 .red-text {color: red;}
</style><h2 class="red-text" color=red;>CatPhotoApp</h2>
So how can you change the color of the H2 element to red?
那么如何將H2元素的顏色更改為紅色?
選項1:內聯CSS (Option 1: Inline CSS)
One way would be to use inline CSS to style the element directly.
一種方法是使用內聯CSS直接為元素設置樣式。
Like with the other methods, formatting is important. Take a look again at the code above:
與其他方法一樣,格式化也很重要。 再看一下上面的代碼:
<h2 class="red-text" color=red;>CatPhotoApp</h2>
To use inline styling, make sure to use the style
attribute, and to wrap the properties and values in double quotes ("):
要使用內聯樣式,請確保使用style
屬性,并將屬性和值包裝在雙引號(“)中:
<h2 class="red-text" style="color: red;">CatPhotoApp</h2>
選項2:使用CSS選擇器 (Option 2: Use CSS selectors)
Rather than using inline styling, you could separate your HTML, or the structure and content of the page, from the styling, or CSS.
除了使用內聯樣式外,您還可以將HTML或頁面的結構和內容與樣式或CSS分開。
First, get rid of the inline CSS:
首先,擺脫內聯CSS:
<style>h2 .red-text {color: red;}
</style><h2 class="red-text">CatPhotoApp</h2>
But you need to be careful about the CSS selector you use. Take a look at the <style>
element:
但是您需要注意所使用CSS選擇器。 看一下<style>
元素:
h2 .red-text {color: red;
}
When there's a space, the selector h2 .red-text
is telling the browser to target the element with the class red-text
that's child of h2
. However, the H2 element doesn't have a child – you're trying to style the H2 element itself.
當有空格時,選擇器h2 .red-text
告訴瀏覽器使用h2
的子級red-text
類定位元素。 但是,H2元素沒有孩子-您正在嘗試設置H2元素本身的樣式。
To fix this, remove the space:
要解決此問題,請刪除空格:
h2.red-text {color: red;
}
Or just target the red-text
class directly:
或直接將red-text
類作為目標:
.red-text {color: red;
}
翻譯自: https://www.freecodecamp.org/news/changing-h2-element-color/