CSS属性

Tim 6 2025-03-15

记录一下开发中使用到的CSS属性

transition

可以为一个元素在不同状态之间切换的时候定义不同的过渡效果。它允许在属性值变化时添加动画效果,使变化更加平滑。

/* Apply to 1 property */
/* property name | duration */
transition: margin-right 4s;

/* property name | duration | delay */
transition: margin-right 4s 1s;

/* property name | duration | timing function */
transition: margin-right 4s ease-in-out;

/* property name | duration | timing function | delay */
transition: margin-right 4s ease-in-out 1s;

/* Apply to 2 properties */
transition:
  margin-right 4s,
  color 1s;

/* Apply to all changed properties */
transition: all 0.5s ease-out;

/* Global values */
transition: inherit;
transition: initial;
transition: unset;

问题

opacity

指定一个元素的不透明度

当父元素设置了 opacity 属性,会影响其子属性。推荐两个常用方法:

使用RGBA

为背景色添加透明度Alpha 值:

.parent {
    background-color: rgba(255, 255, 255, 0.5); /* 白色背景,50% 透明度 */
}

使用伪元素

使用 ::before::after 伪元素来创建一个与父元素相同大小的透明层,然后将子元素放置在这个透明层之上。这里原先是 hover 改变父元素的透明度,现改成对伪元素修改:

.parent{
  /*自定义属性*/
}

.parent::before{
  content: "";
  position: absolute;
  border-radius: 5px;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: inherit; // 如有需要可设置具体背景色
  transition: background-color ease 150ms;
  z-index: 1;
}

// hover时仅改变伪元素的背景透明度
.parent:hover::before {
	background-color: rgba(0, 0, 0, 0.4); // 根据需要调整颜色与透明度
}