开发者

Centering a label

I have a div with some text inside and absolute position. I c开发者_高级运维an set the left or the right, but is there a way to set the center, so Div's text would expand in both directions.

So far I could only think about creating exstremly long div and centering text inside.


If your div is positioned absolutely, you can simply set it's left property so that it's centered.

Example:

HTML:

<div class="outer">
    <div class="inner">Some text...</div>
</div>

CSS:

.outer {
    position: relative;
    width: 900px;
}
.inner {
    position: absolute;
    width: 500px;
    top: 0;
    left: 200px;
}

If you don't know the width of the inner element, you'll have to rely on javascript.

Here's an example using jQuery:

var $el = $('.inner');

$el.css('left',
    ( $el.parent().width() - $el.width() ) / 2
);

and here's the fiddle: http://jsfiddle.net/aa93G/ . Play around with the text inside .inner, and you'll see that the text stays centered.


  • to centralize inner text and inline elements use text-align: center in the parent element.
  • If you're dealing with block elements, you should use margin: auto in the element itself. but you must first set a width for the element, otherwise it will just occupy the whole width of the parent.
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜