0

我有一个网站,我在网站上有 div 垂直和水平居中。它的当前内容是25,因此水平居中工作。如果我更改内容,我将不得不编辑width它的宽度和宽度的margin-left一半。每次进入网站时内容都会发生变化,这将不起作用,我需要一个解决方案。

我该如何解决?我可以检测文本的宽度并使用 js 或 jQuery设置width&吗?margin-left

#output {
    position: absolute;

    top: 50%;
    margin-top: -160px;

    color: #6FA673;
    font: 200pt Aleo;
    font-weight: bold;
    left: 50%;

    width: 296px;
    margin-left: -148px;
}

谢谢!

编辑: 这是给你们的 JSFiddle!与数字 25 完美搭配,但其他任何东西都会有点偏离 - 垂直。

JSFiddle!

4

3 回答 3

1

我刚看到你的 jsfiddle,同时我用 HTML/CSS 编造了一些东西,试图弄清楚你在寻找什么(对我来说类似于灯箱 :))

http://codepen.io/anon/pen/dgKls

从你的jsfiddle这个?http://jsfiddle.net/b4TTK/13/

#output, html, body {

    height:100%;

    width:100%;

    margin:0;

    display:table;

}

body {

    display:table-cell;

    vertical-align:middle;

    text-align:center;

}

#output {

    position: absolute;

    color: #6FA673;

    font: 200pt Arial;

    font-weight: bold;

    line-height:0

}

虽然没有那么流畅

于 2013-06-21T16:11:25.227 回答
1

你说...

如果我更改内容,我将不得不将宽度编辑为它的宽度,并将左边距编辑为宽度的一半。

...不,您不必那样做。你只需要一个更好的 CSS 解决方案。另一种方法是简单地将内容居中,无论您的文本内容有多长或多短。然后你就不必担心编写 js 代码来检测它的 css 属性......

CSS:

   #output {
        position: relative;
        top: 50%;
        margin:0 auto;

        text-align:center;
        color: #6FA673;
        font: 200pt Arial;
        font-weight: bold;
    }

还有我的小提琴

更新 您可以使用简单的 jquery 方法在页面加载时垂直对齐元素...

JS:

var mtop = $(window).height()/2;
$('#output').css({top: mtop});   
于 2013-06-21T16:09:39.863 回答
0

如果您唯一关心的是 margin-left 需要是容器宽度的 1/2,您可以使用以下内容:

$('#output').css('marginLeft', '-'+$('#output').width() /2+'px');

而且当然

width: auto;
于 2013-06-21T16:00:34.630 回答