回答編集履歴

2

コードの修正

2021/01/18 08:15

投稿

Lhankor_Mhy
Lhankor_Mhy

スコア36134

test CHANGED
@@ -44,7 +44,7 @@
44
44
 
45
45
 
46
46
 
47
- [サンプル](https://jsfiddle.net/Lhankor_Mhy/e4kxjqs6/2/)
47
+ [サンプル](https://jsfiddle.net/Lhankor_Mhy/e4kxjqs6/3/)
48
48
 
49
49
 
50
50
 
@@ -80,7 +80,15 @@
80
80
 
81
81
  ```js
82
82
 
83
+ document.querySelectorAll('div').forEach( wrapper =>
84
+
83
- document.querySelectorAll('div').forEach( e => e.style['flex-grow'] = e.querySelector('img').naturalWidth);
85
+ wrapper.querySelector('img').addEventListener('load', e =>
86
+
87
+ wrapper.style['flex-grow'] = e.target.naturalWidth
88
+
89
+ )
90
+
91
+ );
84
92
 
85
93
  ```
86
94
 

1

追記

2021/01/18 08:15

投稿

Lhankor_Mhy
Lhankor_Mhy

スコア36134

test CHANGED
@@ -29,3 +29,91 @@
29
29
  }
30
30
 
31
31
  ```
32
+
33
+
34
+
35
+
36
+
37
+ # 追記
38
+
39
+
40
+
41
+ これではどうでしょうか。ラッピングすることでバグを回避しています。Chrome と Firefox で動作確認済み。
42
+
43
+ 動的にCSSを付与するスクリプトも書きました。
44
+
45
+
46
+
47
+ [サンプル](https://jsfiddle.net/Lhankor_Mhy/e4kxjqs6/2/)
48
+
49
+
50
+
51
+ ```html
52
+
53
+ <section>
54
+
55
+ <div><img src="http://placehold.jp/24/cc9999/993333/300x200.png?text=" alt=""></div>
56
+
57
+ <div><img src="http://placehold.jp/24/cc9999/993333/400x200.png?text=" alt=""></div>
58
+
59
+ <div><img src="http://placehold.jp/24/cc9999/993333/150x200.png?text=" alt=""></div>
60
+
61
+ <div><img src="http://placehold.jp/24/cc9999/993333/300x200.png?text=" alt=""></div>
62
+
63
+ <div><img src="http://placehold.jp/24/cc9999/993333/150x200.png?text=" alt=""></div>
64
+
65
+ <div><img src="http://placehold.jp/24/cc9999/993333/400x200.png?text=" alt=""></div>
66
+
67
+ <div><img src="http://placehold.jp/24/cc9999/993333/300x200.png?text=" alt=""></div>
68
+
69
+ <div><img src="http://placehold.jp/24/cc9999/993333/150x200.png?text=" alt=""></div>
70
+
71
+ <div><img src="http://placehold.jp/24/cc9999/993333/150x200.png?text=" alt=""></div>
72
+
73
+ <div><img src="http://placehold.jp/24/cc9999/993333/300x200.png?text=" alt=""></div>
74
+
75
+ </section>
76
+
77
+ ```
78
+
79
+
80
+
81
+ ```js
82
+
83
+ document.querySelectorAll('div').forEach( e => e.style['flex-grow'] = e.querySelector('img').naturalWidth);
84
+
85
+ ```
86
+
87
+
88
+
89
+ ```css
90
+
91
+ section{
92
+
93
+ display: flex;
94
+
95
+ flex-wrap: wrap;
96
+
97
+ gap: 5px;
98
+
99
+ align-items:flex-start;
100
+
101
+ }
102
+
103
+ div{
104
+
105
+ flex: 1 0 auto;
106
+
107
+ }
108
+
109
+ img{
110
+
111
+ width: 100%;
112
+
113
+ }
114
+
115
+ ```
116
+
117
+
118
+
119
+ ただ、ラッパー要素の高さが画像より少しだけ大きくなるのがなぜなのか、理解できないでいます……