开发者

Centering text in the middle of the parent element

<div id="wrapper" style="height:400px;width:400px;">
 <div id="example">
  Text
 </div>
</div>

I'm looking for a way to get #example into the center (开发者_运维知识库left, right, top, and bottom) of #wrapper.


I think there are multiple ways to achieve what you want. One would be:

#wrapper{
    display:table-cell;
    width:400px;
    height:400px;
    vertical-align:middle;
    border:1px solid red;
}
#example{
    width:200px;
    margin:auto;
    text-align:center;
    background:blue;
}

Demo: http://jsfiddle.net/SsD4Q/3/

I hope that helped somehow!


Try giving #example margin: 0 auto;

The second property is the left/right margin. Auto should center it.

Edit: Sorry that this does not center vertically. I misunderstood. Please see http://www.jakpsatweb.cz/css/css-vertical-center-solution.html for vertical centering.


Vertical alignment is a tricky one unless your using tables.

I suggest you read this aritcle on centering elements. http://css-tricks.com/snippets/css/absolute-center-vertical-horizontal-an-image/


Aligning horizontally however is easy...

Assign a width and use margin:auto

#example {width:100px; margin: 0 auto;}


<div id="wrapper" style="height:400px;weight:400px;">
  <div id="vertical" style="height: 50%; width: 100%; margin-top: -25px"></div>
  <div id="example" style="margin: 0 auto; height: 50px">
    Text
  </div>
  </div>

Set the margin-top minus half the height of the example div


I don't like the current proposed solutions... as they rely on either displaying as table-cells, or using static heights on #example and negative margins.

Here is my proposal, considering #wrapper has fixed height:

  • Set #wrapper's line-height equal to its height;
  • Set #wrapper's text-align to center and vertical-align to center;
  • Set #example's display to inline-block, so it is centered vertically and horizontally but still works as a block;
  • Make #example a span instead, so IE8- allows it to be inline-block.

http://jsfiddle.net/aneves_sw/yse9w/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜