当定位为绝对位置时,将DIV居中,并改变DIV中的内容

Center DIV when positioned as absolute, with changing content in the DIV

本文关键字:DIV 居中 改变 定位 位置      更新时间:2023-09-26

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

我该如何修复它?我是否可以检测文本的宽度并设置width &margin-left与js或jQuery?

#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 !

我刚刚看到了你的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
}

不流畅

你说…

如果我改变内容,我必须将宽度编辑为它的宽度和

…不,你不需要这么做。你只需要一个更好的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});   

如果您唯一关心的是左距需要是容器宽度的1/2,您可以使用以下命令:

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

当然还有

width: auto;