美文网首页
2024-02-29 Tailwind CSS 自学自用其一

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

作者: 网恋被骗二块二 | 来源:发表于2024-02-28 15:37 被阅读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"这样的三倍)

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

  • 你不用费劲想类名,而这么一个类只在当前布局生效
  • 可以少些很多 CSS,让你的 CSS 文件变得精简
  • 当你需要改动样式时会很安全,可以避免影响到其他整体(考虑到复用)

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

  • Designing with constraints(有约束的设计,没怎么看懂这个翻译)对第一点我的理解是,Tailwind 将常用场景都弄好了,你可以直接用,方便样式上统一
  • 响应式,Tailwind 可以很方便的写出响应式页面,而内联无法使用媒体查询
  • 悬停、焦点等 CSS 状态,这也是内联样式无法实现的(这个确实很不错)

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

相关文章

网友评论

      本文标题:2024-02-29 Tailwind CSS 自学自用其一

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