返回

CSS实用锦囊:轻松驾驭那些总是记不住却总要用到的样式

前端

CSS秘籍:掌握那些总是忘掉的样式技巧

在前端开发中,经常会遇到反复使用但又总记不住写法的CSS样式,查阅文档又麻烦又耗时。为了让大家开发更轻松,本文精辟总结了那些总记不住但又常用的CSS样式,涵盖从输入框样式到页面布局、从文本格式到动画效果等常见场景。收藏本文,成为CSS大师指日可待!

一、让input的placeholder更美观

input::-webkit-input-placeholder {
  font-size: 14px;
  color: #ccc;
}

input:-moz-placeholder {
  font-size: 14px;
  color: #ccc;
}

input::-moz-placeholder {
  font-size: 14px;
  color: #ccc;
}

input:-ms-input-placeholder {
  font-size: 14px;
  color: #ccc;
}

二、文本垂直居中

.text-center {
  display: flex;
  align-items: center;
  justify-content: center;
}

三、文本溢出时显示省略号

.text-ellipsis {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

四、圆角元素

.rounded-corners {
  border-radius: 5px;
}

五、给元素添加阴影

.box-shadow {
  box-shadow: 0px 5px 10px rgba(0, 0, 0, 0.2);
}

六、水平居中元素

.center-block {
  margin: 0 auto;
}

七、旋转加载动画

.loading {
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }

  100% {
    transform: rotate(360deg);
  }
}

八、给元素添加点击效果

.button {
  cursor: pointer;
}

.button:hover {
  background-color: #ccc;
}

.button:active {
  background-color: #999;
}

九、响应式导航栏

.navbar {
  width: 100%;
  height: 50px;
  background-color: #333;
}

.navbar ul {
  list-style-type: none;
  display: flex;
  justify-content: space-between;
  padding: 0;
}

.navbar li {
  display: inline-block;
  padding: 10px;
}

.navbar a {
  color: #fff;
  text-decoration: none;
}

.navbar a:hover {
  color: #999;
}

@media (max-width: 768px) {
  .navbar ul {
    flex-direction: column;
  }

  .navbar li {
    display: block;
  }
}

十、全屏背景图片

.full-screen-background {
  background-image: url("image.jpg");
  background-size: cover;
  background-position: center center;
}

掌握这些样式,开发效率将大幅提升,再也不用为那些总记不住的CSS而苦恼。如果你还有其他常用的CSS样式,欢迎在评论区分享。

常见问题解答

  1. 如何让文本在垂直方向上居中,而不是水平方向?

    .text-center-vertical {
      display: flex;
      align-items: center;
    }
    
  2. 如何给一个元素添加多个圆角?

    .rounded-corners {
      border-radius: 5px 10px 15px 20px;
    }
    
  3. 如何制作一个水平滑动的动画?

    .slide-horizontal {
      animation: slide-horizontal 1s linear infinite;
    }
    
    @keyframes slide-horizontal {
      0% {
        transform: translateX(0);
      }
    
      100% {
        transform: translateX(500px);
      }
    }
    
  4. 如何禁用元素的点击效果?

    .disabled {
      pointer-events: none;
    }
    
  5. 如何制作一个视差滚动效果?

    .parallax {
      background-attachment: fixed;
    }