Foreword: Today, the editor found that the a tag can also use the pseudo class: focus to achieve some functions, and share it with you. In the previous article, we used the anchor function of the a tag and input, label to achieve some effects of tab bar switching today. The editor uses another way to add a pseudo-class to the a tag: focus to achieve this effect, and share it with everyone. Also please support us a lot!
In our impression: focus is often used in conjunction with input for the effect of focusing, and today we use it to use it with the a tag.
See the following specific cases:
<!DOCTYPE html>
<html lang="en">
<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">
<title>Document</title>
</head>
<style>
a{
/* remove the default style of a tag*/
text-decoration : none;
/* Convert a tag to an inline block element*/
display: inline-block;
width: 100px;
height: 50px;
text-align: center;
line-height: 50px;
border: 1px solid black;
}
div{
width: 400px;
height: 300px;
display: none;
/* Position all divs absolutely together*/
position: absolute;
}
.a{
background-color: pink;
}
.b{
background-color: green;
}
.c{
background-color:blue;
}
.d{
background-color: yellow;
}
/* When the a tag is focused, the color turns red*/
a:focus{
color: red;
}
/* When the a tag is focused, its next sibling element appears*/
a:nth-of -type(1):focus+.a{
display: block;
}
a:nth-of-type(2):focus+.b{
display: block;
}
a:nth-of-type(3):focus+.c{
display: block;
}
a:nth-of-type(4):focus+.d{
display: block;
}
</style>
<body>
<a href="#">标题一</a>
<div class="a"></div>
<a href="#">标题二</a>
<div class="b"></div>
<a href="#">标题三</a>
<div class="c"></div>
<a href="#">标题四</a>
<div class="d"></div>
</body>
</html>
Note: We can only use nth-of-type(), not nth-child() when we select the first a, because nth-child() is all children under the parent element, and nth-of-type () is the order of children of the same type under the parent element. For example, a:nth-of-type(3) in the above code is the third a tag under the body. If it is written as a:nth-child(3), it will not be selected .
The running effect is as follows:
Click on the title one:
Click on the second heading:
Click on heading three:
Click on heading four:
When the a label is clicked, it will also focus and the color will change. As written in the above code of the editor, a turns red when it is in focus, and it will also be realized.
This will also achieve a tab bar switching effect. I just discovered this writing method today. Is it very simple to achieve this switching effect on many pages in this way? Let's go and have a try.