实用的CSS高级技巧 Part1

作者: LesliePeng | 来源:发表于2017-04-03 14:22 被阅读99次

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;
} 

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

相关文章

  • 实用的CSS高级技巧 Part1

    1 伪类选择器 1.1 :empty 选择内容为空的元素。:not(:empty) 不为空的元素。 举个栗子: 如...

  • CSS教程汇总

    CSS揭秘实用技巧总结 不止于 CSS 灵活运用CSS开发技巧 前端基础篇之CSS世界 你未必知道的49个CSS知...

  • CSS高级技巧

    双飞翼布局 什么是双飞翼布局呢? 事实上,圣杯布局其实和双飞翼布局是一回事。它们实现的都是三栏布局,两边的盒子宽度...

  • CSS 高级技巧

    1.黑白图像 img{filter:grayscale(100%)} 2.使用:not()在菜单上应用/取消应用边...

  • CSS:高级技巧

    学习目标 理解能说出元素显示隐藏最常见的写法能说出精灵图产生的目的能说出去除图片底侧空白缝隙的方法 应用能写出最常...

  • CSS高级技巧

    1、CSS精灵技术 sprite 减少请求次数 合成一张大图片(精灵图,雪剪图)处理网页背景图像的方式 2、字体图...

  • CSS高级技巧

    原文:https://blog.csdn.net/z_x_qiang/article/details/827659...

  • css高级技巧

    元素 显示和隐藏 display:none隐藏对象display:block显示元素隐藏后不有原来位置 visib...

  • 10个非常实用的CSS技巧

    CSS 有很多令人欣喜的小技巧,可以让我们的页面效果更加美丽,现在,就让我们来看看工作中非常实用的 CSS 技巧吧...

  • 10个非常实用的CSS技巧

    CSS 有很多令人欣喜的小技巧,可以让我们的页面效果更加美丽,现在,就让我们来看看工作中非常实用的 CSS 技巧吧...

网友评论

本文标题:实用的CSS高级技巧 Part1

本文链接:https://www.haomeiwen.com/subject/mknnottx.html