晴歩雨描

晴れた日は外に出て歩き、雨の日は部屋で絵を描く

「ブロック(コンテナ)全体は中央揃え(センタリング)+中の要素(複数画像)は左寄せ」をJavaScriptを使わないでCSSのみで実現できる方法

このブログで以前に書いた「ブロック全体は中央揃え+中の複数画像は左寄」をJavaScriptを使わないでCSSのみで実現できる方法が見つかったので、紹介。f:id:art2nd:20170313140402j:plain
「Webクリエイターボックス」の以下の記事のコメント欄で質問したら、「和草イデハナ」さんから「Media Queriesを使えば良いのでは」という返信をもらい、やってみたらうまくいった。Media Queriesを使ってウインドウのmax-widthの幅に応じて、コンテナボックスに適切なwidthを設定する。

≪日本語対応!CSS Flexboxのチートシートを作ったので配布します | Webクリエイターボックス≫

http://www.webcreatorbox.com/tech/css-flexbox-cheat-sheet/

Media Queriesを使ったサンプルが以下。

https://ok2nd.github.io/tool/html/thumbnail-sample-media-queries.html

<div id="contents">
	<div id="gallery">
		<span style="background-image: url('thumbs/001.jpg')"></span>
		<span style="background-image: url('thumbs/002.jpg')"></span>
		...
	</div>
</div>
<style>
#contents {
	margin: 0 auto;
}
#gallery {
	display: flex;
	flex-wrap: wrap;
	align-items: center;
	width: 992px;
	margin: auto;
}
@media screen and (max-width: 1052px) {
	#gallery {
		width: 744px;
	}
}
@media screen and (max-width: 804px) {
	#gallery {
		width: 496px;
	}
}
@media screen and (max-width: 556px) {
	#gallery {
		width: 248px;
	}
}
#gallery span {
	display: flex;
	background-position: center center;
	background-repeat: no-repeat;
	margin: 4px;
	width: 240px;
	height: 240px;
	background-size: contain;
}
</style>