2024-02-29 Tailwind CSS 自学自用其一

2024-02-28  本文已影响0人  网恋被骗二块二

使用 Tailwind,可以通过直接在 HTML 中应用预先存在的类来设置元素样式。

声明:代码来自官网

示意图

如图,在以前写一个样式,需要很多代码

<div class="chat-notification">
  <div class="chat-notification-logo-wrapper">
    <img class="chat-notification-logo" src="/img/logo.svg" alt="ChitChat Logo">
  </div>
  <div class="chat-notification-content">
    <h4 class="chat-notification-title">ChitChat</h4>
    <p class="chat-notification-message">You have a new message!</p>
  </div>
</div>

<style>
  .chat-notification {
    display: flex;
    max-width: 24rem;
    margin: 0 auto;
    padding: 1.5rem;
    border-radius: 0.5rem;
    background-color: #fff;
    box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
  }
  .chat-notification-logo-wrapper {
    flex-shrink: 0;
  }
  .chat-notification-logo {
    height: 3rem;
    width: 3rem;
  }
  .chat-notification-content {
    margin-left: 1.5rem;
    padding-top: 0.25rem;
  }
  .chat-notification-title {
    color: #1a202c;
    font-size: 1.25rem;
    line-height: 1.25;
  }
  .chat-notification-message {
    color: #718096;
    font-size: 1rem;
    line-height: 1.5;
  }
</style>

通过 Tailwind,只需要

<div class="p-6 max-w-sm mx-auto bg-white rounded-xl shadow-lg flex items-center space-x-4">
  <div class="shrink-0">
    <img class="h-12 w-12" src="/img/logo.svg" alt="ChitChat Logo">
  </div>
  <div>
    <div class="text-xl font-medium text-black">ChitChat</div>
    <p class="text-slate-500">You have a new message!</p>
  </div>
</div>

前天学习创建一个next.js项目的时候,我承认看到app/page.tsx这个首页文件className里写的密密麻麻的 Tailwind,感觉很不优雅(代码我已经删了,但最长的绝对是"p-6 max-w-sm mx-auto bg-white rounded-xl shadow-lg flex items-center space-x-4"这样的三倍)

当然,官方表示这样做的好处分别有:

又有一个疑问,既然 Tailwind 也需要写那么长,为什么不直接写内联样式?
官方对此提出相比于内联样式,Tailwind 的几个优点:

最后,官方表示维护 Tailwind 比大型的 CSS 文件要容易许多,很多国外大厂也在用,并且效果很好。

上一篇 下一篇

猜你喜欢

热点阅读