首页 > 解决方案 > Css:检查显示应该隐藏的容器

问题描述

我想在我的页面上做简单的标签,所以我有 3 个标签和 3 个部分。问题是在第一部分我可以看到所有部分容器,在第二个 2 和最后一个。它应该是简单的一个选项卡的一个部分。

我错过了什么?

我的 html 和代码https://codepen.io/wojsza/pen/XWMOXXm

.display__tabs {
  display: flex;
  flex-wrap: wrap; }
  .display__tabs--tab {
    display: none; }
    .display__tabs--tab:checked ~ .display__tabs--label ~ .display__tabs--content {
      display: block; }
  .display__tabs--label {
    cursor: pointer;
    padding: 25px;
    color: #2e2e2e; }
    .display__tabs--label:hover {
      color: #aeaeae;
      background-color: #2e2e2e;
      font-weight: bold;
      text-decoration: underline; }
  .display__tabs--content {
    width: 100%;
    padding: 20px;
    order: 1;
    display: none; }

和html:

<div class="display__tabs">
    <input type="radio" class="display__tabs--tab" id="display-module-info" name="module" checked="checked" />
    <label class="display__tabs--label" for="display-module-info">Info</label>
    <div class="display__tabs--content">
      <p>Module</p>
    </div>

    <input type="radio" class="display__tabs--tab" id="display-module-wsu" name="module" />
    <label for="display-module-wsu" class="display__tabs--label">Wsu</label>
    <div class="display__tabs--content">
        <p>
            WSU
        </p>
    </div>

    <input type="radio" class="display__tabs--tab" id="display-module-sections" name="module" />
    <label for="display-module-sections" class="display__tabs--label">Sections</label>
    <div class="display__tabs--content">
        <p>
            SECTION
        </p>
    </div>
</div>

标签: htmlcss

解决方案


你快到了!只需要将“~”改为“+”即可。

你想在这部分改变你的CSS:

.display__tabs--tab:checked ~ .display__tabs--label ~ .display__tabs--content {
      display: block; 
}

.display__tabs--tab:checked + .display__tabs--label + .display__tabs--content {
      display: block; 
}

这是由 ~ 的 css 选择器导致的,它选择了一般同级,而您想使用 +,因为设置为隐藏和阻塞的单选元素是相邻同级。参考https://levelup.gitconnected.com/understanding-use-of-the-and-symbols-in-css-selectors-95552eb436f5


推荐阅读