在其中使用div而不使用margin auto

时间:2013-10-14 05:06:29

标签: html css css3 css-float css-position

尝试了文本对齐中心和自动边距,两者都不起作用,我不想习惯使用'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;
}

5 个答案:

答案 0 :(得分:7)

首先,使用margin: auto;

要将圆圈置于圆圈中心,您可以使用定位技术,例如position: absolute;。在这里,我在内圈使用position: absolute;,而不是使用值top分配left50%属性,而是使用margin-top和{ {1}}并扣除margin-leftheight的1/2。

为什么要扣除width?正如我已经说过,我正在扣除32pxwidth总数的一半,因此这也包括您的元素的height,其设置为border,这会使您的元素{{1}分别在2px64px中。

height width符号,我使用vertical-align属性,因为我只能看到一个垂直对齐的字符(你没有说过,但从技术上讲,我可以假设是什么形状你在寻找),或者你也可以使用+,但你需要将容器元素设置为line-height

Demo


最后但并非最不重要,您应该将vertical-align: middle;标记嵌套在内圈display: table-cell;内。

span

答案 1 :(得分:3)

Here's一个更清洁的解决方案。

只有一个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%;
}

答案 2 :(得分:1)

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

//float: left;

Working fiddle

答案 3 :(得分:1)

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

 .circle{

         position: relative;
         width: 120px;
         height: 120px;
         border-radius: 50%;
         border: 2px solid #DDD;
         margin:0 auto;
        }

答案 4 :(得分:0)

看看这个fiddle。你写了float:left;并希望将图像居中。删除float:left;,它可以正常工作。

相关问题