昨天看到Matt Griffin在Twitter上发的一个推文:
终于找到了一个好方法,使用
简单方便,再也不要麻烦的单独使用
- :not(:last-of-type)
了,不错!
- :last-of-type
我以前也没有想到过这种用法,这个小小的技巧能省去很多时间和代码。下面让我解释一下,比如说,我们要美化一个文章列表。
- <!-- This is what your html would look like -->
- <ul class="posts">
- <li class="post">
- <a href="/link-to-post/" title="Permalink to post">
- <h2>Post Title</h2>
- <small>Thurs, Feb 16, 2017<small>
- </a>
- </li>
- </ul>
我以前的实现方法是这样的,其实是很笨的方法!
- .posts {
- list - style: none;
- margin: 0;
- padding: 0;
- }
- .post {
- border - bottom: 1px solid#eee;
- margin - bottom: .5rem;
- padding - bottom: .5rem; & :last - child {
- border - bottom: 0;
- margin - bottom: 0;
- padding - bottom: 0;
- }
- }
这CSS的目的是要让列表的文章之间有间隔,但最后一个不需要。这个时候,
就大限神威了!
- :not(:last-of-type)
- .post: not(: last - of - type) {
- border - bottom: 1px solid#eee;
- margin - bottom: .5rem;
- padding - bottom: .5rem;
- }
使用
,我们省掉了5行代码。试想在我们编写的其它代码中都使用这种技巧,不知道要省掉多少工夫。下面是一个实例演示。
- not(:last-of-type)
来源: http://www.webhek.com/post/css-tips-not-last-of-type.html