エレメントを水平に垂直に中央に配置するにはどうすればいいですか?

1582 ワード

この問題は大きく2つのタイプに分けられ、要求に応じて、要素が幅を広げて設定されているかどうかを見ます.
一、要素の幅が広く設定されている(デフォルトは350 px*300 px)
1.絶対位置の利用
#box{
	position: fixed;
	left: 0;
	right: 0;
	bottom: 0;
	top: 0;
	margin: auto;
}

2.まず要素の左上隅を中央点に配置し、自身の幅の半分を左と上に移動します(marginを使用します).
#box{
	position: absolute;
	left: 50%;
	top: 50%;
	margin-left: -150px;
	margin-top: -175px;
}

3.要素の左上隅を中央点に配置し、自身の幅の半分を左と上に移動します(transformを使用して平行移動)
#box{
	position: fixed;
	left: 50%;
	top: 50%;
	transform: translate(-150px,-175px);
}

4.まず要素の左上隅を中央点に位置決めし、自身の幅の半分を左と上に移動します(calc計算を使用します).
#box{
	position: absolute;
	left: 50%;
	top: 50%;
	top:calc(50% - 150px);   /*          */
	left:calc(50% - 175px); 
}

4.親要素がある場合はflexフレックスモデルを使用できます
#father{
	display: flex; 
	justify-content: center;
	align-items: center;
	height: 500px;
	width: 700px;
	background-color: aquamarine;
}

二、幅が固定されていなければ
1.transformサポート率
#box{
	position: fixd; 
	left: 50%;
	top: 50%;
	transform: translate(-50%,-50%);
}

2.親要素がある場合でもflexフレックスモデルを使用できます.
#father{
	display: flex; 
	justify-content: center;
	align-items: center;
	height: 500px;
	width: 700px;
	background-color: aquamarine;
}

3.初期の書き方は、互換性が最適です.自動サブエレメントの面積は親エレメントの4分の1です.
#box{
	width:50%; 
	height:50%; 
	background:pink; 
	position:absolute; 
	top:0; 
	right:0; 
	bottom:0; 
	left:0; 
	margin:auto;
}

よく使うのは多分これだけで、私が書いていないものがあるかもしれませんが、残りのみんなは自分で発掘します.