给定一个已知尺寸的 div
,例如 width: 300px; height: 200px
,将其垂直和水平放置在屏幕中间的最简单方法是什么? 示例
我对最新的 Firefox 感兴趣(不需要 IE hack)。
请仅使用 CSS,不要使用 Javascript。
Given a div
with known dimensions, say width: 300px; height: 200px
, what is the easiest method to place it in the middle of the screen both vertically and horizontally ? Example here
I'm interested in latest Firefox (no need for IE hacks).
CSS only please, no Javascript.
发布评论
评论(5)
将其放置在距窗口/父容器 50% 的位置,并使用负边距大小,即元素宽度/高度的一半:)
您可能需要设置
高度: 100%
,在body
和html
上编辑:这是一个有效的示例。
Position it 50% from the window/parent container and use a negative margin size that's half of the elements width/height :)
You might need to set
height: 100%
, on both thebody
andhtml
Edit: Here's a working example .
在不支持 IE 的情况下,使用
display: table
和display: table-cell
实际上很容易实现。以下是 HTML 的更新:
CSS:
并预览:http://jsfiddle.net/we8BE/
Without supporting IE, this is actually pretty easy to achieve using
display: table
anddisplay: table-cell
.Here's an update to your HTML:
CSS:
And to preview: http://jsfiddle.net/we8BE/
我不知道这是否是最简单的方法,但它似乎有效。
http://www.infinitywebdesign.com/research/cssverticalcentereddiv.htm
I don't know if this is the simplest way, but it seems to work.
http://www.infinitywebdesign.com/research/cssverticalcentereddiv.htm
您愿意使用哪些方法?例如 CSS 达到什么级别 - 2 或 3? JavaScript? jQuery?我的第一个想法是,由于 div 可以通过
margin-left: auto;
和margin-right: auto;
水平居中,也许可以尝试margin: auto;
对于所有 4 个面。让我知道它是否有效。What methods are you open to using? For example CSS up to what level - 2 or 3? Javascript? jQuery? My first thought is that, since divs can be centred horizontally through
margin-left: auto;
andmargin-right: auto;
, maybe trymargin: auto;
for all 4 sides. Let me know if it works.最简单的?众多 jQuery 中心插件之一可用的...
The easiest? One of the numerous jQuery center plugins available...