7

水平方向と垂直方向の両方で、画面の中心から DIV を中央に配置する必要があります。DIV のサイズがわかりません。また、div はposition:fixed;.

div のサイズがわからないため、この負のマージン トリックは機能しません。 top:50%; left:50%; magin-top:-100; margin-left:-100;

は機能せず、垂直方向にも中央揃えmargin-left: auto; margin-right: auto;にならないため、機能しません。position:fixed;margin-top:auto; margin-bottom:auto;

私はこの方法を見つけました:display: table-cell; vertical-align: middle;エーテルは機能しません。

JavaScript で getComputedStyle を使用して div コンテンツのサイズを取得し、その位置を修正する方法を知っていますが、div コンテンツが変更されるたびに JS をトリガーしたくないため、純粋な CSS ソリューションが必要です.

4

4 に答える 4

4

css テーブルを使用して、高さが不明なボックスを垂直方向に中央揃えにすることができます。ボックスの高さは、その内容によって決まります。ボックスのposition: fixedプロパティを使用するこのデモを参照してください。ボックスの幅も設定されます。

これは IE <= 7 の回避策です。

#table {
  height:100%;
  text-align:center;
  white-space: nowrap;
}
#container {
  display: inline;
  zoom: 1;
  text-align: left;
  vertical-align: middle;
}
#IEcenter {
  height: 100%;
  width: 1px;
  display: inline;
  zoom: 1;
  vertical-align: middle;
}
#container * {
  white-space: normal;
}

これはあなたの要件を満たしていますか?

于 2012-05-20T17:28:03.400 に答える
1

デモを見てください(高さは不明、幅は設定されています)。

css テーブルを使用できます (この例では、html がテーブルで、body がテーブルセルです)。マークアップ:

<body>

    <div id="container">
        <h1>Lorem ipsum</h1>
        <p>At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.</p>
    </div>

</body>

CSS:

html {
  margin: 0;
  padding: 0;
  height: 100%;
  width: 100%;
  display: table;
}
body {
  margin: 0;
  padding: 0;
  display: table-cell;
  vertical-align: middle;
}
#container {
  width: 400px;
  margin: 0 auto;
  background: #ffea00;
  border: 2px solid #ff9800;
}

IE <=7 の回避策が必要ですか (IE <=7 は table | table-cell を認識しないため)?

于 2012-05-20T08:31:57.063 に答える
0

このようなものは機能しますか?これも使用しますdisplay: table-cellが、機能するには2つのdivタグが必要です...display: tableスタイルが指定された親タグ。

z-index:-1;注意: centerbaseクラスに追加しました。デザインに基づいてこれを微調整することをお勧めします。

<style>
.centerbase{
    display: table; 
    vertical-align: middle;
    height:100%;
    width:100%;
    text-align:center;
    position:fixed;
    z-index:-1;
}
.centerpane{
    display: table-cell; 
    vertical-align: middle;
}
</style>
<div class="centerbase">
    <div class="centerpane">
        <img src="https://www.google.com/images/srpr/logo3w.png" />
    </div>
​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​&lt;/div>

センターペイン内で中央揃えになっていないテキストを追加する必要がある場合は、センターペイン内に別のdivを追加し、次のようにスタイルを指定できtext-align:left; width:400px; margin:0px auto;ます。この追加のdivの幅を指定する必要があります。

于 2012-05-20T06:31:38.873 に答える