javascript - 以绝对方式定位时居中 DIV,DIV 中的内容不断变化

标签 javascript jquery html css width

我有一个网站,网站上有一个垂直和水平居中的 div。它的当前内容是 25,因此水平居中。如果我更改内容,我必须将 width 编辑为它的宽度,并将 margin-left 编辑为宽度的一半。由于每次您进入网站时内容都会发生变化,这将无法正常工作,我需要一个解决方案。

我该如何解决?我可以检测文本的宽度并使用 js 或 jQuery 设置 widthmargin-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!

最佳答案

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

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

}

虽然没有那么流畅

关于javascript - 以绝对方式定位时居中 DIV,DIV 中的内容不断变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17239416/

相关文章:

javascript - 如何使用javascript在对象数组中执行计算

javascript - 当所选选项禁用时禁用按钮提交

javascript - 本地存储网络数据的不同方式

javascript - 揭示模块模式变量问题

javascript - jquery/javascript 安全

jquery - jquery中动态打印ul id名称

javascript - jQuery 验证插件错误摘要

html - 垂直对齐彼此相邻的两个 div 到相同的高度?

html - 如何在文本旁边 float 图像,中间有间隙

javascript - 输入字段标记验证以 C 或 G 开头