0

ここで何が間違っているのかわかりませんが、2 つの div と、次のような h1 要素 (または P1) があるとしましょう。

<div class="wrapper">
 <div class="top">
    <h1>Content header</h1>
 </div>
</div>

要素を内側の div の「中央の中央」に表示します。つまり、直接の親です。これを実現するために、margin-top:50% と margin-left:50% を指定します。これにより、div の中央中央に向かって正確にレンダリングされることを理解しています。しかし、それは真ん中に到達しますが、完全に中央には到達しません. 実際、クラスラッパーを持つ外側のdivに対して相対的に配置されているようです。

ここでjsfiddleを使用してこれを再作成しました:

http://jsfiddle.net/KLRsN/

セレクターの指定が間違っていますか、それとも位置付け自体が間違っていますか?

4

2 に答える 2

1

-テキストはまだ垂直方向に完全に中央揃えされていないため、上記の回答は完全に正しいとは言えません。

.wrapper{
  margin:5px;
  max-height:250px;
  min-height:250px;/*not required only height:250px will do*/
  border:1px solid green;
}

.content
{
  margin:5px;
  border:1px solid black;
  height:100px;/*you have to give the parent element a height and a width within which you wish to center*/
  width:100px;
  position:relative;/*giving it a position relative so that anything inside it will be positioned absolutely relative to this container*/
  text-align:center;/*aligning the h1 to the center*/
}
.content h1{
border:1px solid black;
 position:absolute;
top:50%;
  left:50%;
  line-height:50px;
  width:50px;
    margin-left:-25px;/*half the width of the h1 so that it exactly centers*/
  margin-top:-25px;/*half the height of the h1 so that it exactly centers*/
}

説明:

-ever 要素はhtml長方形のボックスの形をしているので、適用するmargin-top:50%と、そのボックスの上部が親要素の 50% に揃えられ、ボックス内のテキストには揃えられません。-これが、テキストが正確に中央に配置されていない理由です。

-親要素 (h1 を中央に配置する要素) に幅と高さを指定することも不可欠です。

探していることを行う正しい方法は、絶対位置と相対位置を使用することです。

.container-相対的な位置h1の値と絶対的な値を与える

- h1 に幅と高さを指定することで、幅の半分に等しい負の左マージンと、高さの半分に等しい負の上マージンを適用して、テキストが正確に中央に配置されるようにします。

于 2013-01-08T11:19:07.957 に答える
0

テキスト コンテンツを中央に表示する場合は、 text-align:center を使用するか、h1 タグに幅を適用して margin:auto を使用できます。垂直方向に中央に配置するには、相対位置と top:50% を使用します。このcssを試してください

.wrapper{
   height:250px;
   min-height:250px;
   border:1px solid green;
  }

 .content{
  position:relative;
  top:50%;
   border:1px solid black;
 }
 .content h1{
   border:1px solid blue;
   margin:auto;
   width:100px;
   background:red
 }

それが役に立てば幸い

于 2013-01-08T09:20:25.467 に答える