绿岛之北

好读书,不求甚解;每有会意,便记下笔记。

导航

css小技巧::not()选择器的妙用

比如,要实现下面的效果(例如:一个列表的最后一项没有边框):

See the Pen gmrGOV by yyc (@Gavin-YYC) on CodePen.

一般的文档结构如下:

<!-- 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>

解决这个问题的一般思路是,先给所有的项都设置border-bottom,然后在单独去掉最后一项的边框:

ul {
	margin: 0;
	padding: 0;
	list-style: none;
}
ul li {
	border-bottom: 1px solid #eee;
	margin-bottom: .5rem;
	padding-bottom: .5rem;
	&:last-child {
		border-bottom: 0;
		margin-bottom: 0;
		padding-bottom: 0;
	}
}

上面的代码没有任何问题,也会十分友好的工作,但是,我们完全可以换一种思路:不用先设置所有项的样式,在把最后一项去掉,相反,刚开始就把最后一项去掉!

这就是:not()的魅力:

li:not(:last-of-type) {
  border-bottom: 1px solid #eee;
  margin-bottom: .5rem;
  padding-bottom: .5rem;
}

最后补充

在CSS Selectors 4中,:not()具有更强大的功能,实现更复杂的选择器(目前safari已经完全支持)。

参考:

https://theboldreport.net/2017/02/css-tip-use-not-to-save-time-and-lines-of-code/?utm_source=frontendfocus&utm_medium=email

posted on 2017-03-03 11:18  绿岛之北  阅读(538)  评论(0编辑  收藏  举报