一、半透明边框

background-clip 可以调整背景颜色的覆盖范围,它默认值是 border-box,我们可以重新设置其值为 padding-box,然后将 border 设置为半透明的。

  1. .exercise1{
  2. border: 10px dashed red;
  3. background: yellow;
  4. background-clip: border-box/padding-box;
  5. }

image.png image.png

二、多重边框

box-shadow 、outline 可以模拟边框的效果,box-shadow 可以模拟无数个,outline 只能模拟 1 个

  1. .exercise2-1 {
  2. background: yellowgreen;
  3. box-shadow: 0 0 0 10px #655, 0 0 0 15px deeppink, 0 2px 5px 15px rgba(0, 0, 0, 0.6);
  4. }
  5. .exercise2-2 {
  6. background: yellowgreen;
  7. border: 10px solid #655;
  8. outline: 5px solid deeppink;
  9. }

image.png

三、灵活的背景定位

background-position 设定背景图片的位置,background-origin 可以设置背景图片的定位基准,它默认值是 padding-box,我们修改成 content-box。

background 是一种 CSS 简写属性,用于一次性集中定义各种背景属性,写法可以参看「MDN」

  1. .exercise3-1 {
  2. font-weight: bold;
  3. background: url(../img/add.png) no-repeat bottom right yellowgreen;
  4. background-size: 50px;
  5. background-position: right 20px bottom 20px;
  6. }
  7. .exercise3-2 {
  8. font-weight: bold;
  9. background: url(../img/add.png) bottom right no-repeat yellowgreen;
  10. background-size: 50px;
  11. background-origin: content-box;
  12. }
  13. .exercise3-3 {
  14. font-weight: bold;
  15. background: url(../img/add.png) no-repeat right yellowgreen;
  16. background-size: 50px;
  17. background-position: calc(100% - 20px) calc(100% - 20px);
  18. }

image.png

四、边框内圆角

实现边框内圆角有两种方式,一种是两个 div 嵌套,一种是在一个 div 上添加 box-shadow 和 outline 属性。

  1. .exercise4-11 {
  2. background: #655;
  3. }
  4. .exercise4-12 {
  5. background: tan;
  6. border-radius: .8em;
  7. padding: 1em;
  8. }
  9. .exercise4-2 {
  10. background: tan;
  11. border-radius: .8em;
  12. box-shadow: 0 0 0 10px #655;
  13. outline: 20px solid #655;
  14. }

image.png

五、条纹背景

background 中的 linear-gradient 函数可以实现渐变和条纹,需指定颜色和色标。linear-gradient 本质上是用 CSS 方式生成一张图片,所以我们可以使用 background-size 等属性设置。repeating-linear-gradient 可以实现斜向条纹。

  1. .exercise5-1 {
  2. background: linear-gradient(#fb3, #58a);
  3. }
  4. .exercise5-2 {
  5. background: linear-gradient(#fb3 20%, #58a 60%);
  6. }
  7. .exercise5-3 {
  8. background: linear-gradient(#fb3 50%, #58a 50%);
  9. background-size: 100% 50px;
  10. }
  11. .exercise5-4 {
  12. background: linear-gradient(#fb3 33.3%, #58a 0, #58a 66.6%, yellowgreen 0);
  13. background-size: 100% 52px;
  14. }
  15. .exercise5-5 {
  16. background: linear-gradient(to right, #fb3 50%, #58a 0);
  17. background-size: 50px 100%;
  18. }
  19. .exercise5-6 {
  20. background: repeating-linear-gradient(60deg, #fb3, #fb3 15px, #58a 0, #58a 30px);
  21. }

image.png
image.png
image.png
image.png
image.png
image.png

「@浪里淘沙的小法师」