HTML,CSS: Create tab display and switch content

Other language site
ja ja
Google Translate
  • -

    シェア
  • ---

    LINEで送る
  • -

    はてなブックマーク
    ブックマーク
  • -

    pocket
  • -

    rss
html5 css3 logo

Switch between tabs with HTML and CSS alone. JavaScript is not used.

First of all, let's look at the sample code. You can actually switch between tabs in result display.

:checked pseudo-class

The point of tab switching is to use the CSS: checked pseudo-class.

It is linked to the checked attribute of the HTML input element. The checked attribute of HTML is an attribute that if an input element has a checked attribute, that element becomes selected.

In the sample code, the input element of tab 1 has a checked attribute as an initial value.

Customize radio button to tab

For HTML users, customize the radio button and use it for tabs. Because only one tab can be selected at any time, the radio button is easy to divert as a function.

Just by clicking the radio button, the checked attribute of the input element is automatically switched, so use this operation for switching tabs as is.

Since the radio button needs only internal switching function, it is hidden with display: none. The tab display is expressed by the label element adjacent to the radio button.

Tab switching CSS

This is the only CSS for switching tabs with this code.

.radio:checked + .tab {
background-color: rgba(0, 0, 255, 0.3);
}

.tab-view {
display: none;
}

#tab1:checked ~ .tab-box > #tab-view1 {
display: block;
}
#tab2:checked ~ .tab-box > #tab-view2 {
display: block;
}
#tab3:checked ~ .tab-box > #tab-view3 {
display: block;
}

CSS controls the following operations.

  • The tab with the checked attribute changes to blue and turns it into active color
  • Initialize all content areas of the tab with "display: none" hidden
  • When the checked attribute is attached to each tab and becomes active, the linked content area is displayed as "display: block"

Although all content areas are initialized with "display: none", since the checked attribute is attached to tab1 when displaying the Web page, the content area of tab1 is displayed at the beginning.

Finally

:checked pseudo class is a function available from CSS3. It is almost compatible with the current browser, so you will not mind.

SNS also distributes articles.
Leave a Reply

*

If you like this article, share it!