这些复选标记是如何绘制的?

时间:2014-05-02 20:55:45

标签: css

我正在阅读有关CSS的MDN参考站点中的伪元素,而在article about ::before pseudo-element中,他们使用简单的待办事项列表作为示例。其代码如下:

HTML

<ul>
  <li>Buy milk</li>
  <li>Take the dog for a walk</li>
  <li>Exercise</li>
  <li>Write code</li>
  <li>Play music</li>
  <li>Relax</li>
</ul>

CSS

li {
  list-style-type: none;
  position: relative;
  margin: 2px;
  padding: 0.5em 0.5em 0.5em 2em;
  background: lightgrey;
  font-family: sans-serif;
}

li.done {
  background: #CCFF99;
}

li.done::before {
  content: '';
  position: absolute;
  border-color: #009933;
  border-style: solid;
  border-width: 0 0.3em 0.25em 0;
  height: 1em;
  top: 1.3em;
  left: 0.6em;
  margin-top: -1em;
  transform: rotate(45deg);
  width: 0.5em;
}

的Javascript

var list = document.querySelector('ul');
list.addEventListener('click', function(ev) {
  if( ev.target.tagName === 'LI') {
     ev.target.classList.toggle('done'); 
  }
}, false);

我得到了Javascript代码的功能,我希望复选标记是图像,但它们是由CSS代码绘制的。我可以看到关于什么以及如何绘制它的说明在哪里,但我无法理解这些说明。

我也不知道如何谷歌(因为我不知道CSS中这个技术的名称),所以我真的被困在这里。它是如何工作的?

2 个答案:

答案 0 :(得分:2)

li.done::before { /* This creates a (pseudo) element that is (by default) placed before the content, but is hidden (by default). */
  content: ''; /* This makes this (pseudo) element actually appear. */
  position: absolute; /* This makes it not push the content or affect it in anyway and also makes it act as if it has some sort of display: inline-block; */

  /* These create a right and bottom border and give a width and a height (width * 2) to this (pseudo) element, so you get a reversed L shape. */
  border-color: #009933; /* 
  border-style: solid;
  border-width: 0 0.3em 0.25em 0;
  height: 1em;
  width: 0.5em;

  /* These position this (pseudo) element relatively to its real/owner element, the LI, since it has position: relative. */
  top: 1.3em;
  left: 0.6em;
  margin-top: -1em;

  /* This rotates this (pseudo) element. When you rotate a reversed L, it looks like a check mark. */
  transform: rotate(45deg);
}

答案 1 :(得分:1)

li.done::before规则正在创建一个空白框(content: '';),然后设置右边距和下边距(0 0.3em 0.25em 0;)的样式,然后将其旋转45度(transform: rotate(45deg); )做一个复选标记。