实用的CSS高级技巧 Part1

1 伪类选择器

1.1 :empty 选择内容为空的元素。:not(:empty) 不为空的元素。

举个栗子:

<body>
  <div class="Alert">
    <p>Success! Your profile has been updated.</p>
  </div>
  <div class="Alert">
  </div>
</body>
.Alert {
  border: 3px solid darkgreen;
  margin: 1em;
  padding: 1em;
  background-color: seagreen;
  color: white;
  border-radius: 4px;
}
Screen Shot 2017-04-03 at 12.15.04 PM.png

如果想让空的alert隐藏可以:

.Alert:empty {
  display: none;
 } 

但更简单的方法是:

.Alert:not(:empty) {
  border: 3px solid darkgreen;
  margin: 1em;
  padding: 1em;
  background-color: seagreen;
  color: white;
  border-radius: 4px;
} 

这样的嵌套式使用伪类选择器的例子还有很多
比如:not(:last-child),:not(:first-child)

1.2 选择同类元素中的第一个/第n个/唯一一个等。也非常实用。

first-of-type
last-of-type
only-of-type

nth-of-type(odd)
nth-of-type(even)
nth-of-type(3)
nth-of-type(4n+3)

2.calc()实现响应式设计

比如一个这样结构的网页,包含nav,main,aside三部分。

Screen Shot 2017-04-03 at 1.19.38 PM.png
nav {
  position: fixed;
  top: 0;
  left: 0;
  width: 5rem;
  height: 100%;
}
aside {
  position: fixed;
  top: 0;
  right: 0;
  height: 100%;
  width: 20rem;
}

当屏幕尺寸变化的时候,希望保持当前的布局,让中间的content随之变化,只需要一行css就能实现了。

main {
 margin-left: 5rem;
 width: calc(100% - 25rem);
}

如下图gif动图展示效果:


responsivecontent.gif

再加上一些media query,就是一个完整的针对移动设备和pc的响应式css。

3.用vh,vw规定元素大小

经常被使用到的单位是px,em,rem
你有没有用过更简单的vh,vw呢,这两个单位是相对于当前viewport的百分比。可以很简单的控制元素在viewport中的相对位置:

.Box {
  height: 40vh;
  width: 50vw;
  margin: 30vh 25vw;
}

只需要这一点点css就能让box这个元素不论viewport size如何变化都保持永远居中。因为height+marginTop+ marginBottom = 100vh, width+marginLeft+marginRight = 100vw

alwaycenter.gif

用这样的方法很简单就能写出一个整页page上下滑的网页效果:

ezgif.com-resize.gif

没有用到任何js,非常简单的css,如下:

section {
  width: 100vw;
  height: 100vh;
  
  display: flex;
  align-items: center;
  justify-content: center;
  text-align: center;
  
  background-size: cover;
  background-repeat: no-repeat;
  background-attachment: fixed;
} 

如果觉得有用,请给我点个赞吧(ง •̀_•́)ง!

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 问答题47 /72 常见浏览器兼容性问题与解决方案? 参考答案 (1)浏览器兼容问题一:不同浏览器的标签默认的外补...
    _Yfling阅读 13,815评论 1 92
  • 本文转载自:众成翻译译者:为之漫笔链接:http://www.zcfy.cc/article/239原文:http...
    极乐君阅读 7,417评论 1 62
  • 1.class 和 id 的使用场景? 类选择器允许以一种独立于文档元素的方式来指定样式。该选择器可以单独使用,也...
    草鞋弟阅读 2,489评论 0 1
  • #我的第一个文档#
    魔芋Brace阅读 384评论 0 1
  • 上了大学,有这样一件事很尴尬——原来你以前没有男(女)朋友不是因为学校禁止早恋。看过很多关于上大学的鸡汤文,认为大...
    2d2d68835291阅读 468评论 2 1