您的位置:首页 > 其它

更改H2元素的颜色

2020-08-21 10:47 281 查看

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/

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: