今回はレイアウトに便利なdisplay:flexの小技をご紹介します。
サンプルと失敗例を載せてあります。失敗例をみるとflexにより、画像が引き延ばされてしまっています。今回はこれを改善しつつ、ブラウザ幅を変更しても縦横比を保って画像が拡大縮小するhtmlを作成します。
<html>
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>デモ</title>
<meta name="description" content="">
<meta name="keywords" content="">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="css/index.css">
</head>
<body>
<main ontouchstart="">
<div class="backgroundBox">
<div class="Container">
<p class="title">サンプル</p>
<div class="contentsBox">
<div class="imgBox"><img src="images/file1/sample.png"></div>
<p class="text">サンプルサンプルサンプルサンプルサンプルサンプルサンプルサンプルサンプルサンプルサンプルサンプルサンプルサンプルサンプルサンプルサンプルサンプルサンプルサンプルサンプルサンプルサンプルサンプルサンプルサンプルサンプルサンプルサンプルサンプルサンプルサンプルサンプルサンプルサンプルサンプルサンプルサンプルサンプルサンプルサンプルサンプルサンプルサンプルサンプルサンプルサンプルサンプルサンプルサンプルサンプルサンプルサンプルサンプルサンプルサンプルサンプルサンプルサンプルサンプルサンプルサンプルサンプルサンプルサンプルサンプルサンプルサンプルサンプルサンプルサンプルサンプルサンプルサンプルサンプルサンプルサンプルサンプルサンプルサンプルサンプルサンプルサンプルサンプルサンプル</p>
</div>
</div>
</div>
</main>
</body>
</html>
<ポイント>
・imgタグの直前にdivタグを入れる。(親要素contentsBox、子要素はimgBoxとtext)
<css>
※index.cssの中身
* {
margin: 0;
padding: 0; }
img {
max-width: 100%; }
html {
font-size: 62.5%; }
.backgroundBox {
background-color: whitesmoke; }
.Container {
max-width: 780px;
margin: 0 auto;
padding-top: 10px;
padding-bottom: 50px; }
.contentsBox {
display: flex;
justify-content: space-between; }
.text {
max-width: 380px;
font-size: 1.5rem;
padding-left: 10px; }
.title {
text-align: center;
font-size: 2.0rem; }
<ポイント>
・contentsBoxに対してflexを適用
写真とテキストを並べる。flex内の子要素は親要素の余ったスペースを埋めようとして、子要素を延ばすように設定されている。⇒これにより画像が伸びてしまうが、今回は画像の前にdivタグを入れることで、imgの代わりにdivタグが延びてくれる。
一行記述を追加するだけで、画像の延びを回避できましたね。
以上。