【问题标题】:How can I make the label's text appear next to the toggle when the toggle itself uses the label for its styling当切换器本身使用标签进行样式设置时,如何使标签的文本显示在切换器旁边
【发布时间】:2020-03-18 14:25:59
【问题描述】:

我写了一个小切换组件,可以用来代替复选框。

它的工作方式是标签元素本身就是切换,这意味着如果单击切换或标签,它应该可以访问并工作。

我遇到的问题是我无法让文本出现在滑块旁边,因为添加填充或任何类型的边距会扭曲滑块皮肤。

现场演示在这里:https://svelte.dev/repl/84cfc5281b5d4289b99b222b338f48ae?version=3.20.1

代码由以下 CSS 组成:

.switch {
    position: relative;
    display: inline-block;
    width: 60px;
    height: 34px;
  }

  .switch input {
    opacity: 0;
    width: 0;
    height: 0;
  }

  .slider {
    position: absolute;
    cursor: pointer;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: #ccc;
    -webkit-transition: 0.4s;
    transition: 0.4s;
    border-radius: 34px;
  }

  .slider:before {
    position: absolute;
    content: "";
    height: 26px;
    width: 26px;
    left: 4px;
    bottom: 4px;
    background-color: white;
    -webkit-transition: 0.4s;
    transition: 0.4s;
    border-radius: 50%;
  }

  input:checked + .slider {
    background-color: #2196f3;
  }

  input:checked + .slider {
    box-shadow: 0 0 1px #2196f3;
  }

  input:checked + .slider:before {
    -webkit-transform: translateX(26px);
    -ms-transform: translateX(26px);
    transform: translateX(26px);
  }

以及以下html:

<label class="switch">
  <input type="checkbox" bind:checked />
  <span class="slider" />
  <span>Accept Terms</span>
</label>

显然,简单的解决方法是将文本移出标签,但随后我失去了可访问性,这并不理想。

【问题讨论】:

    标签: html css


    【解决方案1】:

    由于开关元素具有position: relative,而slider 具有固定宽度,因此您可以将position: absolute 与文本一起添加到&lt;span&gt;

    .slider + span {
      position: absolute;
      left: 70px;
    }
    

    然后你可以随意定位它。
    您也可以使用white-space: nowrap 将文本放在一行中。

    【讨论】:

      【解决方案2】:

      您可以通过将文本跨度定位为绝对来做到这一点:

      span:last-child {
          position: absolute;
          white-space: nowrap;
          left: calc(100% + 10px);
          top: 6px
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多