2014-07-10 81 views
0

我想在CSS中创建一个非常简单的按钮,但无法让我的按钮中的箭头位于我的圆圈中心。DIV与CSS中心DIV

我用:

top: 50% 
left: 50% 

尝试和我的中心圈div中我的箭格,当然,这只是我的中心箭头格的左上角,而不是中心位置。

我该如何将div完美地集中在div中?我最好喜欢一个解决方案,我的两个div的宽度和高度无关紧要,所以我可以在以后轻松更改它们。

我当前的代码: http://jsfiddle.net/zhWGx/

+0

http://jsfiddle.net/zhWGx/3/ –

回答

2

试试这一个,让你的三角形position:absolute,然后顶,左底,对的将是0.制作margin:auto。然后你就完成了。

.triangle 
{ 
    width: 0; 
    height: 0; 
    border-style: solid; 
    border-width: 5px 0 5px 5px; 
    border-color: transparent transparent transparent red; 

    position: absolute; 
    top: 0; 
    left: 0; 
    right:0; 
    bottom:0; 
    margin:auto; 
} 

链接:http://jsfiddle.net/Vigiliance/zhWGx/4/

附:

当你使用这种方法时,你会诅咒IE。

1

你可以试试这个,如果你的圈子始终相同的大小:http://jsfiddle.net/zhWGx/1/

.triangle 
{ 
width: 0; 
height: 0; 
border-style: solid; 
border-width: 10px 0 10px 17.3px; 
border-color: transparent transparent transparent #ffffff; 

position: relative; 
display: block; 
margin: 10px auto ; 
top: 10px; 

} 
0

http://jsfiddle.net/Oliboy50/zhWGx/14/

如果要调整三角形位置你想要的方式:

.triangle 
{ 
    width: 0; 
    height: 0; 
    border-style: solid; 
    border-width: 10px 0 10px 17.3px; 
    border-color: transparent transparent transparent #ffffff; 

    position: absolute; /* absolute (the parent is relative) */ 
    top: 50%; 
    left: 50%; 
    margin-top: -10px; /* triangle height/2 */ 
    margin-left: -6px; /* triangle width/2 (6.85px) or what you want */ 
} 
1

这应该修复它

.triangle 
    { 
     width: 0; 
     height: 0; 
     border-style: solid; 
     border-width: 10px 0 10px 17.3px; 
     border-color: transparent transparent transparent #ffffff; 
     background:linear-gradient(transparent, transparent, transparent, #FFFFFF); 
     position: relative; 
     margin-left: 15px; 
     top:24% 

    } 
2

如果你想能中心的元素与未知尺寸,您可以对该元素使用转换(翻译)。

transform: translate(-50%, -50%); 
-webkit-transform: translate(-50%, -50%); 
-moz-transform: translate(-50%, -50%); 
-o-transform: translate(-50%, -50%); 
-ms-transform: translate(-50%, -50%); 

http://jsfiddle.net/zhWGx/23/

注意,这是只支持现代浏览器。

+0

这很好!但正如你在现代浏览器中所说的=) – Izekid

+1

事实上,只要你不需要支持Internet Explorer 7和8,这是一个简单的解决方案,并且可以在每种情况下工作。 –

0

你可以试试:

.triangle { 
width: 0; 
height: 0; 
border-style: solid; 
border-width: 10px 0 10px 17.3px; 
border-color: transparent transparent transparent #ffffff; 
position: relative; 
top: 25%; 
left: 40%; 
} 
0

如果您的div中只有文字,你可以这样做:

.inside-div { 
    display: inline: // for IE 
    display: inline-block; 
    text-align: center; 
} 

否则:

.parent-div { 
    position: relative; 
} 
.inside-div { 
    position: absolute; 
    left: 50%; 
    top: 50%; 
    width: 500px; 
    margin-left: -250px; 
    height: 500px; 
    margin-top: -250px; 
} 

像这样的事情http://jsfiddle.net/zhWGx/27/,但在这种情况下,您应该计算三角形的几何位置并设置边距。