如何在列表项标记之前放置复选框

时间:2021-05-04 23:49:42

标签: css

背景: 我有一个项目列表,每个项目都有一个用于禁用/启用的复选框。
我也把有序的数字放在文字前面

还有一些与复选框切换无关的可变状态

<ol>
  <li>
    <input type="checkbox" />
    Special text
    <span style="color:green;">True (changable state)</span>
  </li>
</ol>

如何在列表项标记(有序数字)之前放置复选框?


注意: 当我在解释这似乎不可能时;我想通了,请参阅下面的答案。
我提到了(可变状态)来解释为什么我不想将复选框放在文本的右侧。

1 个答案:

答案 0 :(得分:0)

input[type="checkbox"] {
   position: absolute; /* Also removes element from document flow */
   left: 0; /* Place at the left of its containing element */
}

ol {
   position: relative; /*
      This magic line seems to do nothing, but
      for `absolute`ly positioned elements,
      the containing element is the nearest parent
      whose position is not `static`.

      The left of the <li> doesn't work (see purple border)
      so naturally the <ol> gets the position: relative;
      since it contains some space before the li::marker
   */
   
   padding-left: 3em; /* Hardcoded space */
   border-left: 2px solid orange;
}

li {
   border: 2px solid purple;
}
<ol>
  <li>
    <input type="checkbox" />
    Special text
    <span style="color:green;">True (changable state)</span>
  </li>
</ol>

MDN absolute 位置:https://developer.mozilla.org/en-US/docs/Web/CSS/position#values
MDN 包含块:https://developer.mozilla.org/en-US/docs/Web/CSS/Containing_block

奇妙的是,此解决方案对于您想放置在标记之前的任何其他元素也很有帮助