2012-12-21 22 views
0

我试图在垂直和水平方向上在div中居中放置一个Character。
我已经使用了以下的CSS来实现。DIV中的字符居中

margin : 0 auto; //attempt1 
    text-align:center; //attempt2 

两者都没有工作,尝试2只是水平对齐字符。
但我也需要垂直对齐。

My Code is here

任何线索,以实现这一目标?

+0

您是否尝试过Google?你不是第一个遇到这个问题的人。 – Vucko

+1

div的高度是固定的还是流体的? –

回答

1

这是你如何解决它:

首先将字符包装在一个元素中:

<div id="DivMenu"> 
    <div id="character">R</div> 
</div> 

然后设置下列CSS:

#DivMenu{ 
    ... 
    text-align:center; 
} 

#character{ 
    position:relative; 
    top:50%; 
    margin-top:-10px 
} 

Working example

+0

它的工作..但你为什么硬编码边缘顶?它会在所有决议中兼容吗? –

+1

http://jsfiddle.net/tutspack/A3kw4/32/ – underscore

+0

@RajaprabhuAravindasamy:页边距与角色高度的一半成正比,所以它的居中位置正确。只要角色本身具有相同的高度(例如,如果更改字体大小,则必须更改边距),它将适用于所有分辨率。 – JCOC611

0

跨浏览器水平对齐有点棘手。

在你已提供的示例的情况下,你可以使用:

line-height:100px; 

对于其他情况下,你需要使用JavaScript和绑定:

$.fn.vAlignBlock = function() { 
     return this.each(function(i){ 
       var ah = $(this).height(); 
       var ph = $(this).parent().height(); 
       var mh = (ph - ah)/2; 
     $(this).css('margin-top', mh); 
     }); 
}; 


$.fn.vAlignInlineBlock = function() { 
    return this.each(function(i) { 
     var h = $(this).height(); 
     var oh = $(this).outerHeight(); 
     var mt = (h + (oh - h))/2; 
     $(this).css("margin-top", "-" + mt + "px"); 
     $(this).css("top", "50%"); 
     $(this).css("position", "absolute"); 
    }); 
}; 
0

我经常使用的技术是包你想集中在一个block元素的东西。它要求你知道你想要居中的宽度和高度。 Here is a demo

<div> 
    <span>R</span> 
</div> 

然后你的风格的span元素(或任何你想要的,但保持它的语义!)是这样的:

span { 
    width:10px; 
    height:20px; 
    margin:-10px 0 0-5px; /* margin-top is minus half your height, margin-left is minus half your width */ 
    top:50%; left:50%; 
    position:absolute; 
    display:block; 
} 

如果你不想无用的元素到DOM的表象目的,您可以将文本节点的line-height与容器的高度相匹配。缺点是如果你的文本跨越两行,它将不可避免地搞砸你的设计,因为line-height异常高。 Here is a demo

div { 
    [...] 
    width: 200px; 
    height: 200px; 
    text-align:center; 
    line-height:200px; 
} 
0

这里的jsfiddle http://jsfiddle.net/HLet2/1/

<div id="DivMenu"> 
    <p>R</p> 
</div> 


#DivMenu 
{ 
position:absolute; 
-webkit-border-radius: 999px; 
-moz-border-radius: 999px; 
border-radius: 999px; 
behavior: url(PIE.htc); 
background: #ccc; 
border: 2px solid #2F2E2E; 
width: 10%; 
height: 12%; 

} 

#DivMenu p 
{ 
    text-align:center; 
    margin-top:50%; 
} 
​ 
0

一种不同的方法是使用好老line-height创建垂直对齐方式。这个想法是使行高与高度相同。然后text-align: center为横向。这适用于我测试过的所有主流浏览器,并且是最简单的解决方案。

对准属性是从的样式的其余在本实施例中分隔:

<html> 
<head> 
<title>Untitled Document</title> 
<style type="text/css"> 

#DivMenu 
{ 
    background: #CCC; 
    border: 2px solid #2F2E2E; 
    width: 100px; 
    height: 100px; 

    text-align: center; 
    line-height: 100px; 
} 

</style> 
</head> 

<body> 
<div id="DivMenu"> 
    R 
</div> 
</body> 
</html> 
0

依然为垂直居中另一个简单的想法是删除height属性和添加填充到顶部和底部,每其中一半是原来的高度。当然,对于水平对中,请使用文本对齐:

text-align: center; 
padding-top: 6%; 
padding-bottom: 6%;