1

テキストをdivの中央に水平に配置しようとしています。

CSS:

#parent {
      background-color: #eee;
      height: 48px;
      text-align: center;
}
#colLeft {
      background-color: #ff8b8b;
      height: 48px;
      display: inline;
      float: left;
}
#colRight {
      background-color: #c3d0ff;
      height: 48px;
      display: inline;
      float: right;
}

HTML:

<div id="parent" style="width:100%">
      <div id="colLeft">left left left left</div>
      Title
      <div id="colRight">right</div>
 </div>

 <div style="width:100%; text-align:center">
      Title - this one is really centered.
 </div>

ただし、「タイトル」というテキストは、消費するスペースを考慮して中央に配置されている#colLeftように見えるため、ブラウザの幅に関して実際には中央に配置されていません。

どんなにスペース#colLeftをとっても、テキストを真に中央に配置できる方法はありますか?

4

3 に答える 3

1

あまりお勧めできませんが、このJSFiddleのようなことを行うことができます。

#parent {
      background-color: #eee;
      height: 48px;
      text-align: center;
}
#colLeft {
      background-color: #ff8b8b;
      height: 48px;
      display: inline;
      float: left;
}
#colRight {
      background-color: #c3d0ff;
      height: 48px;
      display: inline;
      float: right;
}
.title{
    position: absolute;
    width: 100px;
    left: 50%;
    margin-left: -50px;
}

<div id="parent" style="width:100%">
      <div id="colLeft">left left left left</div>
    <div class="title">Title</div>
      <div id="colRight">right</div>
 </div>

 <div style="width:100%; text-align:center">Title - this one is really centered.</div>​

タイトルを作成しposition:absoluteます。幅を付けてください。left: 50%margin-left:幅のマイナス半分。それは中心にとどまります。しかし、私はこれを行うことを本当にお勧めしません...

于 2012-12-16T21:59:26.347 に答える
1

Titleを次のようなdivで囲む場合:

<div style="position: absolute;left: 50%">Title</div>

あなたはWebkitが得意です。

于 2012-12-16T22:02:42.243 に答える
0
<div align="left" style="border:5px solid white; text-align:center; position:relative">

<div align="left" style="border:4px solid brown; float:left; width:100px; position:absolute"><span>left</span></div>
<div align="left" style="border:4px solid brown; right:0; width:200px; position:absolute"><span>right</span></div>

<span>really centered</span></div>
于 2012-12-16T22:23:29.927 に答える