我有一个网站,网站上有一个垂直和水平居中的 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,同时我用 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/