使用CSS跨浏览器的div居中对齐 [英] Cross browser div center alignment using CSS
问题描述
什么是使一个 DIV
,其位置是相对
水平和垂直使用CSS最简单的方法?在宽度和高度 DIV
是未知的,也就是说,它应该为每一个 DIV
尺寸,然后在所有主流浏览器。我的意思是居中对齐。
What is the easiest way to align a div
whose position is relative
horizontally and vertically using CSS ? The width and the height of the div
is unknown, i.e. it should work for every div
dimension and in all major browsers. I mean center alignment.
我想使使用水平对齐方式:
I thought to make the horizontal alignment using:
margin-left: auto;
margin-right: auto;
像我一样在这里 。
like I did here.
这是为水平排列良好的跨浏览器解决方案?
Is this a good cross browser solution for horizontal alignment ?
我怎么能这样做垂直对齐方式?
How could I do the vertical alignment ?
推荐答案
水平居中只有当元素的宽度
是已知的可能,否则浏览器想不通哪里开始和结束。
Horizontal centering is only possible if the element's width
is known, else the browser cannot figure where to start and end.
#content {
width: 300px;
margin: 0 auto;
}
这是完全crossbrowser兼容。
This is perfectly crossbrowser compatible.
垂直居中只有当该元素绝对定位,并具有一个已知高度
。绝对定位将然而打破保证金:0汽车;
,所以你需要以不同的方法这一点。您需要设置其顶
和离开
到 50%
和的margin-top
和利润率左
到负半及其<$的C $ C>宽度和高度
分别。
Vertical centering is only possible if the element is positioned absolutely and has a known height
. The absolute positioning would however break margin: 0 auto;
so you need to approach this differently. You need to set its top
and left
to 50%
and the margin-top
and margin-left
to the negative half of its width
and height
respectively.
下面是一个copy'n'paste'n'runnable例如:
Here's a copy'n'paste'n'runnable example:
<!doctype html>
<html lang="en">
<head>
<title>SO question 2935404</title>
</head>
<style>
#content {
position: absolute;
width: 300px;
height: 200px;
top: 50%;
left: 50%;
margin-left: -150px; /* Negative half of width. */
margin-top: -100px; /* Negative half of height. */
border: 1px solid #000;
}
</style>
<body>
<div id="content">
content
</div>
</body>
</html>
这就是说,垂直居中通常很少在现实世界中的应用。
That said, vertical centering is usually seldom applied in real world.
如果宽度和高度真的是预先不知道,那么你就需要抓住的Javascript / jQuery来设置利润率左
和保证金机顶
的价值观和生活的事实,客户端将看到的div迅速在页面加载转移,这可能会导致一个跆拳道?经验。
If the width and height are really unknown beforehand, then you'll need to grab Javascript/jQuery to set the margin-left
and margin-top
values and live with the fact that client will see the div quickly be shifted during page load, which might cause a "wtf?" experience.
这篇关于使用CSS跨浏览器的div居中对齐的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!