This page looks best with JavaScript enabled
⚠️

【Rails × Tailwind】Tailwindだけで画像スライダー

 ·   ·  ☕ 1 分で読めます
✏️

こういうのです。
Image from Gyazo

参考元はTailwind carousel component - examples & templates

できるだけ生CSSを書かずにTailwindで実装しました。

前提

ImageモデルのnameカラムをActiveStorageで紐付けています。
なので、image.name.variant(resize_to_fill: [800, 450])はそれぞれよしなの値にしてください。

実装

if文とかはあまりいい感じの実装じゃないので、どうにかしたい思いはある。
とりあえず叩き台ということで。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<style type="text/css">
  .carousel-open:checked+.carousel-item {
    display: block;
  }
  .carousel-open:checked+.carousel-item .carousel-image {
    position: static;
    opacity: 100;
  }
</style>

<div class="grid gap-8 row-gap-8 lg:grid-cols-2">
  <div class="relative rounded overflow-hidden shadow-md">
    <% if @images.empty? %>
      <%= image_tag 'https://placehold.jp/70/d6d6d6/7d7d7d/800x450.png?text=No%20Image' %>
    <% else %>
      <% @images.each_with_index do |image, index| %>
        <% size = @images.size %>
        <input class="carousel-open" type="radio" id="carousel-<%= index %>" name="carousel" aria-hidden="true" hidden <%= index.zero? ? 'checked' : nil %>>
        <div class="carousel-item hidden">
          <%= image_tag url_for(image.name.variant(resize_to_fill: [800, 450])), class: "carousel-image absolute" %>
          <% if size > 1 %>
            <label for="carousel-<%= (index-1) % size %>" class="w-8 h-8 ml-2 md:ml-3 absolute cursor-pointer rounded-full text-white bg-black bg-opacity-30 hover:bg-opacity-80 inset-y-0 left-0 my-auto flex items-center justify-center">
              <i class="fas fa-angle-left" aria-hidden="true"></i>
            </label>
            <label for="carousel-<%= (index+1) % size %>" class="w-8 h-8 mr-2 md:mr-3 absolute cursor-pointer rounded-full text-white bg-black bg-opacity-30 hover:bg-opacity-80 inset-y-0 right-0 my-auto flex items-center justify-center">
              <i class="fas fa-angle-right" aria-hidden="true"></i>
            </label>
          <% end %>
        </div>
      <% end %>
    <% end %>
  </div>
</div>
Share on

END
END
@aiandrox

 
目次