懒人得以进步。
代码不是越多就越屌,贵在精用。
:not() 的精简
not() 的妙用,去除繁琐的定义 last-child 或 first-child 。
比如一个列表,需要第一个和最后一个不变的颜色保持不变,其他的变成红色背景。
普通写法:
- #example ul li {
- background-color: #f00;
- }
- #example ul li:first-child {
- background-color: transparent;
- }
- #example ul li:last-child {
- background-color: transparent;
- }
精简写法:
- #example ul li:not(:first-child):not(:last-child) {
- background-color: #f00;
- }
:nth-child 的精简
对于标签,我们喜欢点对点的写法,比如前三个标签背景为红色,你也许想到了这种写法
- #example ul li:nth-child(1),
- #example ul li:nth-child(2),
- #example ul li:nth-child(3) {
- background-color: #f00;
- }
完美的实现了前三个标签的红色。也许我们可以精简它,如下面这个
- #example ul li:nth-child(-n+3) {
- background-color: #f00;
- }
相反,除了前三个标签,其他的都需要加上红色背景,只需要去掉 - 号
- #example ul li:nth-child(n+3) {
- background-color: #f00;
- }
这样就能快速达到目的。
CSS 双击控制
CSS 控制双击事件是比较少见的,但却是可以通过简单的「层」控制,来达到双击效果。
如下代码:
HTML
- <span class="double-click"><input type="text" readonly="true" /><a href="http://example.com">Double click</a></span>
CSS
- .double-click {
- position: relative;
- }
- .double-click a {
- position: relative;
- z-index: 2;
- }
- .double-click a:hover,
- .double-click a:active {
- z-index: 4;
- }
- .double-click input {
- background: transparent;
- border: 0;
- cursor: pointer;
- position: absolute;
- top: 0;
- left: 0;
- width: 100%;
- height: 100%;
- z-index: 3;
- }
- .double-click input:focus {
- z-index: 1;
- }
这段代码恰好的运用了 「z-index」 ,是一种 CSS 控制,无法给 JavaScript 传双击状态。
提示:如果需要多个地方运用双击,只需要复制HTML代码到任意地方,修改 a 链接地址。
CSS 渐变背景的动画
CSS 的过渡动画时非常美妙的,但有点不怎么好的是,目前不支持渐变的背景。
恰巧的发现,可以通过背景定位去更改渐变的背景,这使得渐变背景也可以有动画般的过渡。
HTML
- <input type="button" value="渐变按钮" class="transition-bg">
CSS
- .transition-bg {
- padding: 10px 20px;
- border: none;
- border-radius: 4px;
- color: #fff;
- background-image: linear-gradient(#e67e22 0, #d35400 25%,#e74c3c 75%,#c0392b 100%);
- background-size: auto 200%;
- background-position: 0 100%;
- transition: background-position 0.5s;
- }
- .transition-bg:hover {
- background-position: 0 0;
- }
通过增大背景高度,默认时为100% - 200%的视图,悬浮后背景位置移动到 0 - 100% 的视图。
示例为从上往下,但运用背景位置转移,可控制多个方面的滑动,根据实际情况,可达到很棒的效果。
待续...
评论 (0)