如何只使用CSS制作标签?

我正在寻找一个像jQuery标签这样的标签系统,用户可以在这之间切换不同的面板来查看不同的内容:

在此处输入图像描述

但是,我需要在不使用javascript的情况下完成此操作,以便没有启用javascript的用户可以轻松使用该网站。 此外,我想避免导航到不同的静态html页面,每个页面都有与“标签”对应的不同样式。 有什么好方法可以解决这个问题?

实现仅CSS选项卡的简单方法是使用单选按钮!

关键是设置附加到相应按钮的labels样式。 单选按钮本身隐藏在屏幕一侧,有一点绝对定位。

基本的html结构是:

 div#holder input[type="radio"] div.content-holder label div.tab-content (all your tab content goes here) input[type="radio"] ... keep repeating 

关键在于选择器。 我们将使用input[type="radio"]按钮设置样式

 input[type="radio"] { position: absolute; left: -100%; top: -100%; height: 0; display: none; } 

如上所述,这将它们从屏幕的侧面提升。 但是我们如何点击它们呢? 幸运的是,如果您定位label ,它可以为您点击输入!

  

然后我们设计实际标签的样式(为了简洁,我将省略美学风格):

 input[type="radio"] + div.content-holder > label { display: inline-block; float: left; height: 35px; width: 33%; /* or whatever width you want */ } 

现在我们的标签应该看起来像div#holder顶部的“tabs”。 但那些内容呢? 好吧,我们希望默认情况下都隐藏它,所以我们可以使用以下选择器来定位它:

 input[type="radio"] + div.content-holder > div.tab-content { display: none; position: absolute; top: 65px; /* this depends on your label height */ width: 100%; } 

上面的CSS是使其工作所需的最小CSS。 display: none;以外的所有内容display: none; 是实际显示div时你会看到的。 但这在标签中没有显示任何内容,所以…现在怎样?

 input[type="radio"]:checked + div.content-holder > div.tab-content { display: block; } 

上述工作原因是因为:checked伪类。 由于label附加到特定的单选按钮,因此它们会触发:checked单击时:checked 。 这会自动关闭所有其他单选按钮。 因为我们已经在div.content-holder包装了所有内容,所以我们可以使用下一个兄弟CSS选择器+来确保我们只定位特定的选项卡。 (尝试使用~ ,看看会发生什么!)

对于那些不喜欢堆栈片段的人来说,这是一个小提琴 ,这里有一个堆栈片段,对于那些你这样做的人:

 #holder { border: solid 1px black; display: block; height: 500px; position: relative; width: 600px; } p { margin: 5px 0 0 5px; } input[type="radio"] { display: none; height: 0; left: -100%; position: absolute; top: -100%; } input[type="radio"] + div.content-holder > label { background-color: #7BE; border-radius: 2px; color: #333; display: inline-block; float: left; height: 35px; margin: 5px 0 0 2px; padding: 15px 0 0 0; text-align: center; width: 33%; } input[type="radio"] + div.content-holder > div { display: none; position: absolute; text-align: center; top: 65px; width: 100%; } input[type="radio"]:checked + div.content-holder > div { display: block; } input[type="radio"]:checked + div.content-holder > label { background-color: #B1CF6F; } img { left: 0; margin: 15px auto auto auto; position: absolute; right: 0; } 
 

All my content for the first tab goes here.

You can put whatever you want in your tabs!

Any content, anywhere!

Remember, though, they're absolutely positioned. This means they position themselves relative to their parent, div#holder, which is relatively positioned

And maybe I want a picture of a nice cat in my third tab!