html - CSS:使用一个类/id 的编号作为另一个类/id 的值

标签 html css

我创建了一个“仅 CSS”网站,仅使用 CSS/HTML/PHP,带有 CSS 菜单、动态加载内容(图像)和 CSS 放大镜。我不想使用 Javascript/jQuery 或 Cookie,并且该网站到目前为止运行良好。布局确实很难调整以正确适应所有浏览器,但最终我让 Apple-InternetExplorer (Safari) 也能正常工作。

对于菜单,我使用了 "Checkbox Hack" 。但我没有使用复选框,而是使用单选按钮来仅显示一个内容页面。看起来像这样:

<!-- 
We need these input-fields to trigger display:block on another element 
The radio-buttons must use the same "name" to jump between different content-pages. 
(only 1 Radio-Button can be active)
-->
<input type="radio" id="radioactive-1" name="radioactive">
<input type="radio" id="radioactive-2" name="radioactive">

<!-- This simple menu triggers the radio-button with the id (for=id) -->
<label for="radioactive-1">Menu-Entry 1</label>
<label for="radioactive-2">Menu-Entry 2</label>

<!-- Heres the content to display, but it is set to display: none; 
so the content only gets displayed if the correct radio-button is active -->
<div id='content-wrapper'>
    <div id='not-radioactive-1' style='display:none;'></div>
    <div id='not-radioactive-2' style='display:none;'></div>
</div>

该标记已缩短,但我认为它足够清晰。现在我们需要 CSS,这对于使其正常工作非常重要:

input[id="radioactive-1"]:checked ~ #content-wrapper #not-radioactive-1 {
    display:block!important;
}
input[id="radioactive-2"]:checked ~ #content-wrapper #not-radioactive-2 {
    display:block!important;
}

您可以看到这些 CSS 声明可能会变得很长,而且我只需单击一下即可触发不同元素的多种样式。菜单的代码约为 20 KB,非常大。(我的 CSS 文件大小的 50%)

现在我的问题:有没有办法获取输入字段的类号以将其用于内容类?

示例:

input[id="radioactive-$value"]:checked ~ #not-radioactive-$value

我知道一种方法来忽略数字并使用所有 id,包括定义的字符串。

示例:

input[id^="radioactive-"]:checked

我也知道我可以使用 PHP 并只执行一个循环,但最终 CSS 具有相同的大小,因为整个代码都会得到回显。如果可能的话,我正在寻找仅 CSS 的解决方案。我只想缩短代码并加快页面加载速度。

最佳答案

您可以通过在每个部分之前直接插入单选按钮来完成此操作,而无需依赖这些数字:

HTML:

<div id="content-wrapper">
    <input type="radio" id="radioactive-1" name="radioactive">
    <div class="content"></div>

    <input type="radio" id="radioactive-2" name="radioactive">
    <div class="content"></div>
</div>

CSS:

.content {
    display: none;
}

input[name="radioactive"]:checked + .content {
    display: block;
}

只要 for 属性与某些输入匹配,标签在哪里并不重要。

关于html - CSS:使用一个类/id 的编号作为另一个类/id 的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30347155/

相关文章:

html - 如何制作CSS网格的内容包装器 "on top"

javascript - 仅将移动用户重定向到不同的 .html 文件一次

jquery - 垂直3d翻转效果

javascript - 内联 CSS 不适用于 JS 生成的输入

html - 使用 css,如何确保在跨度边界上换行?

jquery - 更改 :hover with jQuery

html - CSS 列样式仅适用于 Chrome 中的一列

html - 如何在 contentPlaceholder 中引用具有特定 ID 的按钮

html - 显示单独的线而不是边框

javascript - 什么影响页面重绘性能?