实用的CSS高级技巧 Part1

1 伪类选择器

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

举个栗子:


  

Success! Your profile has been updated.

.Alert {
  border: 3px solid darkgreen;
  margin: 1em;
  padding: 1em;
  background-color: seagreen;
  color: white;
  border-radius: 4px;
}
实用的CSS高级技巧 Part1_第1张图片
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三部分。

实用的CSS高级技巧 Part1_第2张图片
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;
} 

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

你可能感兴趣的:(实用的CSS高级技巧 Part1)