画像を入れたFlexboxを伸縮させたときに
- 画像のサイズは固定したい
- 画像はFlexboxの伸縮に合わせて比率を維持したまま拡大縮小したい
とか色々あるので作ってみた次第。
HTML
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<div class="parent"> <div class="child child-left"> <p>画像のサイズは常に固定</p> <img src="crown.png"> </div> <div class="child child-center"> <p>Flexboxの大きさに追従<br/>※画像の元サイズ(= 100%)が上限</p> <img src="crown.png"> </div> <div class="child child-right"> <p>Flexboxの大きさに追従<br/>※上限なし</p> <img src="crown.png"> </div> </div> |
CSS
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 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
.parent { max-width: 90%; margin: 0 auto; display: flex; flex-direction: row; flex-wrap: nowrap; justify-content: space-around; } .child { flex-grow: 1; border:1px solid #000; padding: 5px; margin: 0 5px; } .child p { text-align: center; line-height: 1.4rem; font-weight: bold; padding: 10px; border-bottom: 1px dotted #000; } /* 画像のサイズは常に固定 */ .child-left img { /* 幅・高さを具体的に指定する */ width : calc(742px * 0.25); height: calc(800px * 0.25); } /* Flexboxの大きさに追従 ※画像の元サイズ(= 100%)が上限 */ .child-center img { /* 幅もしくは高さを最大100%に設定、もう一方はauto */ max-width: 100%; height: auto; } /* Flexboxの大きさに追従 ※上限なし */ .child-right img { /* 幅もしくは高さを100%に設定、もう一方はauto */ width: 100%; /* 親のサイズ目一杯まで広がる */ height: auto; } |
コメントを残す