1

尝试了 text-align center 和 margin auto ,两者都不起作用,我不想习惯使用'margin hack'进行居中..

http://jsfiddle.net/st9AM/1/

.circle{

float: left;
position: relative;
width: 120px;
height: 120px;
border-radius: 50%;
border: 2px solid #DDD;
}

.inner{
float: left;
position: relative;
width: 60px;
height: 60px;
border-radius: 50%;
border: 2px solid #DDD;
}
4

5 回答 5

7

首先,使用margin: auto;不是黑客

为了让你的圆圈在圆圈内居中,你可以使用定位技术,比如position: absolute;. 在这里,我position: absolute;在内圈上使用,而不是分配值为topand的属性,而不是使用and并减去 and 的1/2 。left50%margin-topmargin-leftheightwidth

为什么要扣分32px?正如我已经说过的那样,我正好扣除了总数的一半widthheight所以这也包括border你的元素,它被设置为2px分别使你的元素64px成为heightwidth

对于符号,我正在使用属性vertical-align,因为我只能看到一个垂直对齐的字符(你没有说,但技术上我可以假设你在寻找什么形状),或者你也可以使用,但你需要设置容器元素到+line-heightvertical-align: middle;display: table-cell;

演示


最后但并非最不重要的一点是,您应该将span标签嵌套在内圈内div

.circle{
   float: left;
   position: relative;
   width: 120px;
   height: 120px;
   border-radius: 50%;
   border: 2px solid #DDD;
}

.inner{
   text-align: center;
   line-height: 60px;
   position: absolute;
   top: 50%;
   margin-top: -31px;
   left: 50%;
   margin-left: -31px;
   width: 60px;
   height: 60px;
   border-radius: 50%;
   border: 2px solid #DDD;
}
于 2013-10-14T05:10:41.970 回答
3

这是一个更清洁的解决方案。

只有一个 HTML 元素。

HTML:

<div class='circle'></div>

CSS:

*
{
    margin: 0;
    padding: 0;
}
.circle, .circle:after
{
    border-radius: 50%;
    border: 2px solid #DDD;
    text-align: center;
}
.circle
{
    width: 120px;
    height: 120px;
    font-size: 0;
}
.circle:before {
    content:'';
    display: inline-block;
    height: 100%;
    vertical-align: middle;
}
.circle:after
{    
    content:'+';
    font-size: 20px;
    padding: 20px 0; /* 2*padding + font size = innerCircle height*/
    display: inline-block;
    vertical-align: middle;
    width: 50%;
}
于 2013-10-14T07:15:02.400 回答
1

你在内圈有“浮动:左”,你不需要

//float: left;

工作小提琴

于 2013-10-14T05:15:12.003 回答
1

删除左浮动并使用边距:0自动;

 .circle{

         position: relative;
         width: 120px;
         height: 120px;
         border-radius: 50%;
         border: 2px solid #DDD;
         margin:0 auto;
        }
于 2013-10-14T05:18:23.483 回答
0

看看这个小提琴。您编写float:left;并希望将图像居中。删除float:left;它,它工作正常。

于 2013-10-14T06:07:37.843 回答