blog

divの縦幅と横幅を固定しない方法

この方法は、幅と高さを厳密に固定せず、親の幅と高さの50%にする必要があります。視覚的な効果が得られるのであれば、似たようなニーズに絞ってこの方法を使うことができます。...

Jul 15, 2020 · 2 min. read
シェア

div の高さと幅を固定せずに、縦方向に中央揃えする方法です。

擬似要素およびinline-block / vertical-alignの設定によって実現されます。

<style>
	.box-wrap:before {
		content: '';
		display: inline-block;
		height: 100%;
		vertical-align: middle;
		margin-right: -0.25em; //スペースの微調整
	}
	.centered {
		display: inline-block;
		vertical-align: middle;
	} 
</style>
<div class="box-wrap" style="height: 200px; background-color: #ccc; text-align: center;" >
 <div class="centered">
 <h1> </h1>
 <p>擬似クラスで縦中央かどうかを確認する</p>
 </div> 
</div>

css3-flex

<style>
	.box-wrap {
		height: 300px;
		justify-content:center; 
		align-items:center;
		display:flex; 
		background-color:#666;
	}
</style>
<div class="box-wrap">
	<div class="centerd">css3-flex</div>
</div> 

css3 ~ie8非対応

css3-transform

<style>
	.box-wrap { 
		width:100%; 
		height:300px; 
		background:rgba(0,0,0,0.7); 
		position:relative;
	}
	.box-content{ 
		position:absolute; 
		background:pink; 
		left:50%; 
		top:50%; 
		transform:translateX(-50%) translateY(-50%); 
		-webkit-transform:translateX(-50%) translateY(-50%); 
	}
</style>
<div class="box-wrap">
 <div class="box-content">css3-transform</div>
</div>

css3 ~ie8非対応

、マージンを設定:効果を達成するために自動

<style>
	.box-wrap {
		position: relative;
 width:100%;
 height:300px;
 background-color:#f00;
 }
	.box-content{
		position: absolute;
		top:0;
		left:0;
		bottom:0;
		right:0;
		width:50%;
		height:50%;
		margin:auto;
		background-color:#ff0;
	}
</style>
<div class="box-wrap">
 <div class="box-content">auto</div>
</div> 

Read next

データ構造バイナリーツリーのトラバーサル

バイナリツリーをトラバースする3つの方法1、前順序トラバーサルNLR3、後順序トラバーサルLRN生成

Jul 15, 2020 · 1 min read