Reputation: 231
I'm trying to change the current tab color in CSS and the tab created using the :target property of CSS. The problem is I can't find the current clicked tab when using the :target property. So I want to show the active tab when I clicked. Also I need to show the first tab by default. Can someone help me to solve it?
Here is my code below:
.tab {
display: flex;
flex-direction: row;
margin-bottom: 30px;
}
.tab li {
color: var(--dark);
margin-right: 15px;
font-size: 22px;
position: relative;
}
.tab li:after {
height: 1px;
content: '';
background-color: rgb(10, 170, 219) !important;
width: 100%;
position: absolute;
left: 0;
}
.tab li h2 {
font-size: inherit;
}
.tab li a {
text-decoration: none;
color: inherit;
}
#tab .tab-content {
display: none;
}
#tab .tab-content:target {
display: block;
}
<div id="tab">
<ul class="tab">
<li>
<h2><a href="#tab1">Tab1</a></h2>
</li>
<li>
<h2><a href="#tab2">Tab2</a></h2>
</li>
</ul>
<div id="tab1" class="tab-content">Content1</div>
<div id="tab2" class="tab-content">Content2</div>
</div>
Upvotes: 0
Views: 87
Reputation: 36
The best way to simulate an actual click event using only CSS is to use the checkbox. It works by attaching a label to an element via the label's for="" attribute and using :checked attribute to detect clicked tab.
Upvotes: 1
Reputation: 2753
Currently your tab switching functionality does not work. Your rules for the display of .tab-content
are with incorrect selectors. Simply move #tab1
and #tab2
inside the main #tab
element. Then the color styling will be easy.
.tab {
display: flex;
flex-direction: row;
margin-bottom: 30px;
}
.tab li {
color: var(--dark);
margin-right: 15px;
font-size: 22px;
position: relative;
}
.tab li:after {
height: 1px;
content: '';
background-color: rgb(10, 170, 219) !important;
width: 100%;
position: absolute;
left: 0;
}
.tab li h2 {
font-size: inherit;
}
.tab li a {
text-decoration: none;
color: inherit;
}
#tab .tab-content {
display: none;
}
#tab .tab-content:target {
display: block;
}
<div id="tab">
<ul class="tab">
<li>
<h2><a href="#tab1">Tab1</a></h2>
</li>
<li>
<h2><a href="#tab2">Tab2</a></h2>
</li>
</ul>
<div id="tab1" class="tab-content">Content1</div>
<div id="tab2" class="tab-content">Content2</div>
</div>
Upvotes: 0