回答編集履歴

1

css

2022/11/27 23:18

投稿

Cocode
Cocode

スコア2314

test CHANGED
@@ -3,7 +3,7 @@
3
3
  - cssの`position: absolute`で重ねる
4
4
  - 順番に`opacity`を`0` <--> `1`を入れ替えていく
5
5
 
6
- ### コード例
6
+ ### コード例(JavaScript編)
7
7
  - 動作確認用サンプル:https://jsfiddle.net/0t18d5zj/1/
8
8
  ```html
9
9
  <div id="main-visual" class="main-visual">
@@ -82,3 +82,70 @@
82
82
  }, sec * 1000);
83
83
  }
84
84
  ```
85
+
86
+ ### コード例(CSS編)
87
+ CSSのみによる実装もお知りになりたいとのことで、コードをご紹介いたします。
88
+
89
+ - 動作確認用サンプル:https://jsfiddle.net/ocfdgp2j/2/
90
+ ```html
91
+ <div id="main-visual" class="main-visual">
92
+ <img class="img" src="https://cdn.shopify.com/s/files/1/0600/3310/6102/t/2/assets/top_1.jpg?ver=220320&v=24797785482821047691647782404" alt="">
93
+ <img class="img" src="https://cdn.shopify.com/s/files/1/0600/3310/6102/t/2/assets/top_2.jpg?ver=220320&v=53756209350512176351647782414" alt="">
94
+ <img class="img" src="https://cdn.shopify.com/s/files/1/0600/3310/6102/t/2/assets/top_3.jpg?ver=220320&v=152939468448035609741647782426" alt="">
95
+ <img class="img" src="https://cdn.shopify.com/s/files/1/0600/3310/6102/t/2/assets/top_4.jpg?ver=220320&v=3071968281155817841647782437" alt="">
96
+ </div>
97
+ ```
98
+ ```css
99
+ /* アニメーションのスピードを設定(画像1枚分の秒数) */
100
+ :root {
101
+ --animation-speed: 4s;
102
+ }
103
+
104
+ .main-visual {
105
+ max-width: 600px;
106
+ aspect-ratio: 2 / 1;
107
+ position: relative;
108
+ }
109
+
110
+ .img {
111
+ width: 100%;
112
+ height: 100%;
113
+ object-fit: cover;
114
+ position: absolute;
115
+ top: 0;
116
+ left: 0;
117
+ opacity: 0;
118
+
119
+ animation-name: fadeImg;
120
+ /* アニメーションの秒数は、1枚分の秒数 × 画像の枚数 */
121
+ animation-duration: calc(var(--animation-speed) * 4);
122
+ animation-iteration-count: infinite;
123
+ }
124
+
125
+ .img:nth-child(1) {
126
+ animation-delay: 0;
127
+ }
128
+
129
+ .img:nth-child(2) {
130
+ animation-delay: calc(var(--animation-speed) * 1);
131
+ }
132
+
133
+ .img:nth-child(3) {
134
+ animation-delay: calc(var(--animation-speed) * 2);
135
+ }
136
+
137
+ .img:nth-child(4) {
138
+ animation-delay: calc(var(--animation-speed) * 3);
139
+ }
140
+
141
+ @keyframes fadeImg {
142
+ 0% {opacity: 0;}
143
+
144
+ /* ここの%は、100% / 画像の枚数 */
145
+ /* 例)100% / 4枚 = 25% */
146
+ 25% {opacity: 1;}
147
+
148
+ /* ここの%は、↑の2倍 */
149
+ 50% {opacity: 0;}
150
+ }
151
+ ```