开发者

How can I center text in a div?

I am new to CSS and don't rea开发者_如何学Golly understand this.

Before I was using tables and it was easy. Now I have 10 divs and each has a number inside. I want to get the numbers to all be in the center of the divs which are all same width.

Is there an easy way to do this?


text-align: center should be enough


I think that besides wanting them to be horizontally in the centre you also mean that they should be vertically in the centre (middle in CSS terminology). Have a look at this CSS sniplet and the JSFiddle with working example: http://jsfiddle.net/yc6s8/

div {
    display: inline-block;
    width: 35px;
    line-height: 35px;
    text-align: center;
}


<div class="test">12345</div>

And in your CSS:

.test{
    text-align: center;
}

Text-align can also take left; or right; to align to left and right. If you want to center the div in it's container you would do:

.test
{
    margin: 0 auto;
}


in your css code just add

div#yourId
{
    text-align:center;
}

if you want to align a specific item in your div you could do the following. let's say this is your html

<div class="myDiv">
<p class="align">21</p>
<p>text goes here</p>
</div>

then in your css code

.align{text-align:center;}

this way you just need to add the class align to the element you want and it will be centered (but this will only work with block elements, the paragraph tag is a block element but for example the span tag is not)

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜