6 CSS の水平および垂直センタリング ソリューション

小云云
リリース: 2018-02-23 09:32:00
オリジナル
1952 人が閲覧しました

この記事では、CSSの水平方向と垂直方向の中央揃えの解決策(6種類)に関する関連情報を主に紹介します。編集者が非常に優れていると考えたので、参考として共有します。編集者をフォローして見てみましょう。皆さんのお役に立てれば幸いです。

準備

要素を作成

<p class="parent">
  <p class="child">child</p>
</p>
ログイン後にコピー

垂直方向と水平方向のセンタリング 解決策 1: 幅がわかっている場合は絶対+マージンの負の値

.parent {
  width:400px;
  height:400px;
  background: red;
  position: relative;
}
.child {
  position: absolute;
  left:50%;
  top:50%;
  background: yellow;
  width:50px;
  height:50px;
  margin-left:-25px;
  margin-top:-25px;
}
ログイン後にコピー

垂直方向と水平方向のセンタリング 解決策 2: 幅と高さが不明な場合は絶対+変換

.parent {
  width:400px;
  height:400px;
  background: red;
  position: relative;
}
.child {
  position: absolute;
  left:50%;
  top:50%;
  transform: translate(-50%,-50%);
}
ログイン後にコピー

垂直中央揃えオプション 3:position+margin:auto

.parent {
  position:relative;
  width:200px;
  height:200px;
  background: red;
}
.child {
  width:80px;
  height:40px;
  background: yellow;
  position: absolute;
  left:0;
  top:0;
  right:0 ;
  bottom:0;
  margin:auto;
}
ログイン後にコピー

垂直中央揃えオプション 4: + 複数行テキストの垂直中央揃え: table-cell+vertical-align:middle;

.parent {
    height: 300px;
    width:400px;
    border: 1px solid red;
    display: table-cell;
    vertical-align: middle;
    text-align: center;
}
.child {
  display: inline-block;
  width:50px;
  height:50px;
  background: blue;
}
/* 或者 */
.parent {
    width: 400px;
    height: 300px;
    display: table-cell;
    vertical-align: middle;
    border: 1px solid red;
    text-align: center;
}
.child {
    display: inline-block;
    vertical-align: middle;
    background: blue;
}
ログイン後にコピー

垂直中央揃えオプション 5: 表示: flex

.parent {
  width:400px;
  height:200px;
  background:red;
  display: flex;
  justify-content:center;
  align-items:center;
}
.child {
  height:100px;
  width:100px;
  background:green;
}
ログイン後にコピー

垂直方向の中央揃えソリューション 6: 疑似要素

.parent {
  width:200px;
  height:200px;
  background:red;
  text-align: center;
}
.child {
  height:100px;
  width:100px;
  background:yellow;
  display: inline-block;
  vertical-align: middle;
}
.parent:before {
  content:"";
  height:100%;
  vertical-align: middle;
  display: inline-block;
}
ログイン後にコピー

関連する推奨事項:

CSS で水平方向と垂直方向の中央揃えを実現する 4 つの方法

HTML 要素の水平方向と垂直方向の中央揃えを設定する方法

方法CSS で水平方向と垂直方向のセンタリングを実現し、2 つの末尾揃えのコード共有を実現します

以上が6 CSS の水平および垂直センタリング ソリューションの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

関連ラベル:
ソース:php.cn
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!