设置链接样式

在设计 links 样式时,了解如何利用伪类来有效地设计其状态非常重要。了解如何设置链接样式以用于内容不同的常见界面功能(例如导航菜单和选项卡)也很重要。我们将在本文中讨论这两个主题。

¥When styling links, it's important to understand how to make use of pseudo-classes to style their states effectively. It's also important to know how to style links for use in common interface features whose content varies, such as navigation menus and tabs. We'll look at both these topics in this article.

先决条件: HTML 基础知识(学习 HTML 简介)、CSS 基础知识(学习 CSS 简介)、 CSS 文本和字体基础知识
目标: 了解如何设置链接状态的样式,以及如何在导航菜单等常见 UI 功能中有效使用链接。

让我们看一些链接

¥Let's look at some links

我们研究了如何根据 创建超链接 中的最佳实践在 HTML 中实现链接。在本文中,我们将以此知识为基础,向你展示设计它们的最佳实践。

¥We looked at how links are implemented in your HTML according to best practices in Creating hyperlinks. In this article we'll build on this knowledge, showing you the best practices for styling them.

链接状态

¥Link states

首先要理解链接状态的概念 - 链接可以存在的不同状态。这些可以使用不同的 pseudo-classes 进行样式设置:

¥The first thing to understand is the concept of link states — different states that links can exist in. These can be styled using different pseudo-classes:

  • 关联:具有目的地的链接(即,不仅仅是命名锚点),使用 :link 伪类设置样式。
  • 访问过:已访问过的链接(存在于浏览器的历史记录中),使用 :visited 伪类设置样式。
  • 徘徊:用户鼠标指针悬停在其上的链接,使用 :hover 伪类设置样式。
  • 重点:获得焦点的链接(例如,由键盘用户使用 Tab key 或类似的东西,或者使用 HTMLElement.focus() 以编程方式集中) - 这是使用 :focus 伪类的样式。
  • 积极的:已激活(例如,单击)的链接,使用 :active 伪类设置样式。

默认样式

¥Default styles

下面的示例说明了默认情况下链接的外观和行为;尽管 CSS 放大并居中文本以使其更加突出。你可以将示例中默认样式的外观和行为与此页面上应用了更多 CSS 样式的其他链接的外观和行为进行比较。默认链接具有以下属性:

¥The example below illustrates what a link will look and behave like by default; though the CSS is enlarging and centering the text to make it stand out more. You can compare the look and behavior of the default stylings in the example with the look and behavior of other links on this page which have more CSS styles applied. Default links have the following properties:

  • 链接带有下划线。
  • 未访问的链接是蓝色的。
  • 访问过的链接是紫色的。
  • 将鼠标悬停在链接上会使鼠标指针变为小手图标。
  • 聚焦链接周围有一个轮廓 - 你应该能够通过按 Tab 键使用键盘聚焦于此页面上的链接。(在 Mac 上,你需要使用 option
    tab ,或通过按启用 全键盘访问:所有控制 选项 Ctrl
    F7 .)
  • 活动链接为红色。尝试在单击链接时按住鼠标按钮。
html
<p><a href="#">A simple link</a></p>
css
p {
  font-size: 2rem;
  text-align: center;
}

注意:此页面上的所有链接示例都链接到其窗口的顶部。空片段 (href="#") 用于创建简单示例并确保包含在 <iframe> 中的实时示例不会损坏。

¥Note: All the link examples on this page link to the top of their window. The empty fragment (href="#") is used to create simple examples and ensure the live examples, which are each contained in an <iframe>, don't break.

有趣的是,这些默认样式与 20 世纪 90 年代中期浏览器早期的样式几乎相同。这是因为用户知道并且已经开始期待这种行为 - 如果链接的样式不同,就会让很多人感到困惑。这并不意味着你根本不应该设置链接样式。这只是意味着你不应偏离预期行为太远。你至少应该:

¥Interestingly enough, these default styles are nearly the same as they were back in the early days of browsers in the mid-1990s. This is because users know and have come to expect this behavior — if links were styled differently, it would confuse a lot of people. This doesn't mean that you shouldn't style links at all. It just means that you shouldn't stray too far from the expected behavior. You should at least:

  • 对链接使用下划线,但不要对其他内容使用下划线。如果你不想在链接下划线,至少以其他方式高亮它们。
  • 让它们在悬停/聚焦时以某种方式做出反应,并在激活时以稍微不同的方式做出反应。

可以使用以下 CSS 属性关闭/更改默认样式:

¥The default styles can be turned off/changed using the following CSS properties:

  • color 为文本颜色。
  • cursor 代表鼠标指针样式 - 除非有充分的理由,否则不应将其关闭。
  • outline 为文本大纲。轮廓类似于边框。唯一的区别是边框占用框中的空间,而轮廓则不占用空间。它只是位于背景的顶部。轮廓是一种有用的辅助功能,因此在不添加另一种指示焦点链接的方法的情况下不应将其删除。

注意:你不仅限于上述属性来设置链接样式 - 你可以自由使用你喜欢的任何属性。

¥Note: You are not just limited to the above properties to style your links — you are free to use any properties you like.

设置一些链接的样式

¥Styling some links

现在我们已经详细了解了默认状态,接下来让我们看看一组典型的链接样式。

¥Now that we've looked at the default states in some detail, let's look at a typical set of link styles.

首先,我们将写出空规则集:

¥To start off with, we'll write out our empty rulesets:

css
a {
}

a:link {
}

a:visited {
}

a:focus {
}

a:hover {
}

a:active {
}

这一顺序很重要,因为链接样式是相互构建的。例如,第一条规则中的样式将应用于所有后续规则。当链接被激活时,它通常也会悬停在上面。如果你以错误的顺序放置这些规则,并且在每个规则集中更改相同的属性,则事情将不会按你的预期进行。要记住顺序,你可以尝试使用 LoVe Fears HAte 等助记符。

¥This order is important because link styles build on one another. For example, the styles in the first rule will apply to all the subsequent ones. When a link is activated, it's usually also hovered over. If you put these in the wrong order, and you're changing the same properties in each ruleset, things won't work as you expect. To remember the order, you could try using a mnemonic like LoVe Fears HAte.

现在让我们添加一些更多信息来正确设置样式:

¥Now let's add some more information to get this styled properly:

css
body {
  width: 300px;
  margin: 0 auto;
  font-size: 1.2rem;
  font-family: sans-serif;
}

p {
  line-height: 1.4;
}

a {
  outline-color: transparent;
}

a:link {
  color: #6900ff;
}

a:visited {
  color: #a5c300;
}

a:focus {
  text-decoration: none;
  background: #bae498;
}

a:hover {
  text-decoration: none;
  background: #cdfeaa;
}

a:active {
  background: #6900ff;
  color: #cdfeaa;
}

我们还将提供一些示例 HTML 以将 CSS 应用到:

¥We'll also provide some sample HTML to apply the CSS to:

html
<p>
  There are several browsers available, such as <a href="#">Mozilla Firefox</a>,
  <a href="#">Google Chrome</a>, and <a href="#">Microsoft Edge</a>.
</p>

将两者放在一起给出了这样的结果:

¥Putting the two together gives us this result:

那么我们在这里做了什么?这看起来确实与默认样式不同,但它仍然为用户提供了足够熟悉的体验,让他们知道发生了什么:

¥So what did we do here? This certainly looks different to the default styling, but it still provides a familiar enough experience for users to know what's going on:

  • 前两条规则对于本次讨论来说并不是那么有趣。
  • 第三条规则使用 a 选择器来消除焦点轮廓(无论如何,不同浏览器的焦点轮廓有所不同)。
  • 接下来,我们使用 a:linka:visited 选择器在未访问和已访问的链接上设置一些颜色变化,以便它们是不同的。
  • 接下来的两个规则使用 a:focusa:hover 将聚焦链接和悬停链接设置为没有下划线和不同的背景颜色。
  • 最后,a:active 用于在链接被激活时为链接提供反转的配色方案,以明确正在发生重要的事情!

主动学习:设计你自己的链接

¥Active learning: Style your own links

在这个主动学习课程中,我们希望你采用我们的空规则集并添加你自己的声明,以使链接看起来非常酷。发挥你的想象力,尽情发挥吧。我们确信你可以想出一些更酷且与上面的示例一样实用的东西。

¥In this active learning session, we'd like you to take our empty set of rules and add your own declarations to make the links look really cool. Use your imagination, go wild. We are sure you can come up with something cooler and just as functional as our example above.

如果你犯了错误,你可以随时使用“重置”按钮进行重置。如果你确实遇到困难,请按“显示解决方案”按钮插入我们上面显示的示例。

¥If you make a mistake, you can always reset it using the Reset button. If you get really stuck, press the Show solution button to insert the example we showed above.

html
<div
  class="body-wrapper"
  style="font-family: 'Open Sans Light',Helvetica,Arial,sans-serif;">
  <h2>HTML Input</h2>
  <textarea
    id="code"
    class="html-input"
    style="width: 90%;height: 10em;padding: 10px;border: 1px solid #0095dd;">
<p>There are several browsers available, such as <a href="#">Mozilla
 Firefox</a>, <a href="#">Google Chrome</a>, and
<a href="#">Microsoft Edge</a>.</p>
  </textarea>

  <h2>CSS Input</h2>
  <textarea
    id="code"
    class="css-input"
    style="width: 90%;height: 10em;padding: 10px;border: 1px solid #0095dd;">
a {

}

a:link {

}

a:visited {

}

a:focus {

}

a:hover {

}

a:active {

}
  </textarea>

  <h2>Output</h2>
  <div
    class="output"
    style="width: 90%;height: 10em;padding: 10px;border: 1px solid #0095dd;"></div>
  <div class="controls">
    <input
      id="reset"
      type="button"
      value="Reset"
      style="margin: 10px 10px 0 0;" />
    <input
      id="solution"
      type="button"
      value="Show solution"
      style="margin: 10px 0 0 10px;" />
  </div>
</div>
js
const htmlInput = document.querySelector(".html-input");
const cssInput = document.querySelector(".css-input");
const reset = document.getElementById("reset");
const htmlCode = htmlInput.value;
const cssCode = cssInput.value;
const output = document.querySelector(".output");
const solution = document.getElementById("solution");

const styleElem = document.createElement("style");
const headElem = document.querySelector("head");
headElem.appendChild(styleElem);

function drawOutput() {
  output.innerHTML = htmlInput.value;
  styleElem.textContent = cssInput.value;
}

reset.addEventListener("click", () => {
  htmlInput.value = htmlCode;
  cssInput.value = cssCode;
  drawOutput();
});

solution.addEventListener("click", () => {
  htmlInput.value = htmlCode;
  cssInput.value = `p {
  font-size: 1.2rem;
  font-family: sans-serif;
  line-height: 1.4;
}

a {
  outline-color: transparent;
  text-decoration: none;
  padding: 2px 1px 0;
}

a:link {
  color: #265301;
}

a:visited {
  color: #437A16;
}

a:focus {
  border-bottom: 1px solid;
  background: #BAE498;
}

a:hover {
  border-bottom: 1px solid;
  background: #CDFEAA;
}

a:active {
  background: #265301;
  color: #CDFEAA;
}`;
  drawOutput();
});

htmlInput.addEventListener("input", drawOutput);
cssInput.addEventListener("input", drawOutput);
window.addEventListener("load", drawOutput);

在链接上包含图标

¥Including icons on links

常见的做法是在链接上包含图标,以提供更多关于链接指向何种内容的指示符。让我们看一个非常简单的示例,它将图标添加到外部链接(指向其他站点的链接)。这样的图标通常看起来像一个指向盒子外面的小箭头。对于本例,我们将使用 来自 icon8.com 的这个很好的例子

¥A common practice is to include icons on links to provide more of an indicator as to what kind of content the link points to. Let's look at a really simple example that adds an icon to external links (links that lead to other sites). Such an icon usually looks like a little arrow pointing out of a box. For this example, we'll use this great example from icons8.com.

让我们看一些 HTML 和 CSS,它们将给我们带来我们想要的效果。首先,一些简单的 HTML 样式:

¥Let's look at some HTML and CSS that will give us the effect we want. First, some simple HTML to style:

html
<p>
  For more information on the weather, visit our <a href="#">weather page</a>,
  look at <a href="https://en.wikipedia.org/">weather on Wikipedia</a>, or check
  out
  <a href="https://www.nationalgeographic.org/topics/resource-library-weather/">
    weather on National Geographic</a>.
</p>

接下来,CSS:

¥Next, the CSS:

css
body {
  width: 300px;
  margin: 0 auto;
  font-family: sans-serif;
}

p {
  line-height: 1.4;
}

a {
  outline-color: transparent;
  text-decoration: none;
  padding: 2px 1px 0;
}

a:link {
  color: blue;
}

a:visited {
  color: purple;
}

a:focus,
a:hover {
  border-bottom: 1px solid;
}

a:active {
  color: red;
}

a[href^="http"] {
  background: url("external-link-52.png") no-repeat 100% 0;
  background-size: 16px 16px;
  padding-right: 19px;
}

那么这是怎么回事呢?我们将跳过大部分 CSS,因为它们与你之前看过的信息相同。然而,最后一条规则很有趣:我们在外部链接上插入自定义背景图片,其方式与我们在上一篇文章中处理 列表项上的自定义项目符号 的方式类似。然而,这一次我们使用 background 简写而不是各个属性。我们设置要插入的图片的路径,指定 no-repeat,这样我们只插入一份副本,然后将位置指定为文本内容右侧的 100%,距离顶部 0 像素。

¥So what's going on here? We'll skip over most of the CSS, as it's just the same information you've looked at before. The last rule, however, is interesting: we're inserting a custom background image on external links in a similar manner to how we handled custom bullets on list items in the last article. This time, however, we're using the background shorthand instead of the individual properties. We set the path to the image we want to insert, specify no-repeat so we only get one copy inserted, and then specify the position as 100% of the way to the right of the text content, and 0 pixels from the top.

我们还使用 background-size 来指定背景图片显示的尺寸。拥有一个更大的图标,然后根据响应式网页设计的需要调整它的大小是很有用的。然而,这仅适用于 IE 9 及更高版本。因此,如果你需要支持较旧的浏览器,你只需调整图片大小并按原样插入即可。

¥We also use background-size to specify the size we want the background image to be shown at. It's useful to have a larger icon and then resize it like this as needed for responsive web design purposes. This does, however, only work with IE 9 and later. So if you need to support older browsers, you'll just have to resize the image and insert it as is.

最后,我们在链接上设置一些 padding-right,为背景图片腾出空间,这样我们就不会与文本重叠。

¥Finally, we set some padding-right on the links to make space for the background image to appear in, so we aren't overlapping it with the text.

最后一句话:我们如何只选择外部链接?好吧,如果你正确编写 HTML 链接,则应该只对外部链接使用绝对 URL — 使用相对链接来链接到你自己网站的其他部分(与第一个链接一样)会更有效。因此,文本 "http" 应该只出现在外部链接中(如第二个和第三个链接),我们可以使用 属性选择器 选择它:a[href^="http"] 选择 <a> 元素,但前提是它们具有 href 属性且值以 "http" 开头。

¥A final word: how did we select just external links? Well, if you are writing your HTML links properly, you should only be using absolute URLs for external links — it is more efficient to use relative links to link to other parts of your own site (as with the first link). The text "http" should therefore only appear in external links (like the second and third ones), and we can select this with an attribute selector: a[href^="http"] selects <a> elements, but only if they have an href attribute with a value that begins with "http".

就是这样了。尝试重新访问上面的主动学习部分并尝试这种新技术!

¥So that's it. Try revisiting the active learning section above and trying this new technique out!

注意:href 值看起来很奇怪 - 我们在这里使用了虚拟链接,它们实际上不会去任何地方。这样做的原因是,如果我们使用真实链接,你将能够在嵌入了实时示例的 <iframe> 中加载外部站点,从而丢失该示例。

¥Note: The href values look strange — we've used dummy links here that don't really go anywhere. The reason for this is that if we used real links, you would be able to load an external site in the <iframe> the live example is embedded in, thereby losing the example.

注意:如果你还不熟悉 backgrounds响应式网页设计,请不要担心;这些在其他地方都有解释。

¥Note: Don't worry if you are not familiar with backgrounds and responsive web design yet; these are explained in other places.

将链接样式设置为按钮

¥Styling links as buttons

到目前为止,你在本文中探索的工具也可以以其他方式使用。例如,悬停等状态可用于设置许多不同元素的样式,而不仅仅是链接 - 你可能想要设置段落、列表项或其他内容的悬停状态的样式。

¥The tools you've explored so far in this article can also be used in other ways. For example, states like hover can be used to style many different elements, not just links — you might want to style the hover state of paragraphs, list items, or other things.

此外,在某些情况下,链接的外观和行为通常类似于按钮。网站导航菜单可以标记为一组链接,并且可以将其样式设置为看起来像一组控制按钮或选项卡,使用户可以访问网站的其他部分。让我们探讨一下如何做。

¥In addition, links are quite commonly styled to look and behave like buttons in certain circumstances. A website navigation menu can be marked up as a set of links, and this can be styled to look like a set of control buttons or tabs that provide the user with access to other parts of the site. Let's explore how.

首先,一些 HTML:

¥First, some HTML:

html
<nav class="container">
  <a href="#">Home</a>
  <a href="#">Pizza</a>
  <a href="#">Music</a>
  <a href="#">Wombats</a>
  <a href="#">Finland</a>
</nav>

现在我们的 CSS:

¥And now our CSS:

css
body,
html {
  margin: 0;
  font-family: sans-serif;
}

.container {
  display: flex;
  gap: 0.625%;
}

a {
  flex: 1;
  text-decoration: none;
  outline-color: transparent;
  text-align: center;
  line-height: 3;
  color: black;
}

a:link,
a:visited,
a:focus {
  background: palegoldenrod;
  color: black;
}

a:hover {
  background: orange;
}

a:active {
  background: darkred;
  color: white;
}

这给了我们以下结果:

¥This gives us the following result:

HTML 定义了带有 "container" 类的 <nav> 元素。<nav> 包含我们的链接。

¥The HTML defines a <nav> element with a "container" class. The <nav> contains our links.

CSS 包括容器的样式及其包含的链接。

¥The CSS includes the styling for the container and the links it contains.

  • 第二条规则说:
    • 该容器是 flexbox。它包含的项目(在本例中为链接)将是弹性项目。
    • 弹性项目之间的间隙将为容器宽度的 0.625%
  • 第三条规则设置链接的样式:
    • 第一个声明 flex: 1 意味着将调整项目的宽度,以便它们使用容器中的所有可用空间。
    • 接下来,我们关闭默认的 text-decorationoutline - 我们不希望它们破坏我们的外观。
    • 最后三个声明是将每个链接内的文本居中,将 line-height 设置为 3 以使按钮具有一定的高度(这也具有使文本垂直居中的优点),并将文本颜色设置为黑色。

概括

¥Summary

我们希望本文已经为你提供了有关链接所需的所有信息 - 目前!我们的样式文本模块中的最后一篇文章详细介绍了如何在你的网站上使用 自定义字体(或网络字体,因为它们更为人所知)。

¥We hope this article has provided you with all you'll need to know about links — for now! The final article in our Styling text module details how to use custom fonts on your websites (or web fonts, as they are better known).