【CSS】天地左右の中央に配置する

天地左右の中央(真ん中)に配置する方法はいくつかあります。その代表的な方法を説明します。

CSSでレイアウトする前の状態はこちら

.content-bodyの中に.content-boxを作ります。

<div class="content-body">
	<div class="content-box"></div>
</div>
.content-body{
	background-color:#ccc;
	width:100%;
	min-height:300px;
}
 
.content-box{
	width:100px;
	height:100px;
	background-color:#999;
	border:1px solid #666;
}

flexboxで天地左右中央に配置する

一番簡単な方法です。親要素にdisplay:flexかけて子要素が中央になるようにしてします。

.content-body{
 
	/*flexboxで天地左右中央*/
	display: flex;
	flex-direction: row;
	flex-wrap: wrap;
	justify-content: center;
	align-items: center;
 
	/*表示用*/
	background-color:#ccc;
	width:100%;
	min-height:300px;
}

positoinで天地左右中央に配置する

positoinを利用する方法です。親要素にrelative、子要素にabsoluteをして親要素に対して天地左右中央にします。

.content-body{
 
	/*positoinで相対対象にする*/
	position: relative;
 
	/*表示用*/
	background-color:#ccc;
	width:100%;
	min-height:300px;
}
 
.content-box{
 
	/*positoinで絶対指定にする*/
	position: absolute;
	top:50%;
	left:50%;
	transform: translateY(-50%) translateX(-50%);
 
	/*表示用*/
	width:100px;
	height:100px;
	background-color:#999;
	border:1px solid #666;
}

positoinでの天地左右中央は、空間が作成されないレイヤー構造になるので、レスポンシブ等によるレイアウトの崩れを気にしなく利用できます。うまく両方使い分けるとよいと思います。

Yuki Nakata

中田デザイン事務所 代表。
WEBデザイナー(フリー)/ WEB講師(非常勤)/ 海外販売(法人)他

お仕事のご相談はお問い合わせフォームへお願いします。