A quick trick to display elements centered on screen is using negative margin and absolute positioning.
An example:
- We need to display a div 500x200 centered on screen
- html <div id='center'>this is the content</div>
- css .center { width: 500px; height: 200px; position:absolute; top:50%; left:50%; margin-left: -250px; margin-top: -100px }
发布评论
评论(4)
可能是这样的:
参考文献:
Google Chrome 样式表:http://codesearch.google.com/codesearch#OAMlx_jo-ck/src/third_party/WebKit/Source/WebCore/css/html.css
<前><代码>中心{
显示:块;
/* 特殊居中能够模拟 html4/netscape 行为 */
文本对齐:-webkit-center
}
Firefox 样式表: http://mxr.mozilla.org/mozilla-central/source /layout/style/html.css
<前><代码>中心{
显示:块;
文本对齐:-moz-center;
}
为什么不使用
标签
作为展示标签,必须执行以下操作毫无意义:
<前><代码>中心{
文本对齐:左对齐;
}
如果可能(即几乎总是),表示应该始终委托给 CSS。
有多种方法可以以不同的方式“居中”不同的事物,但这应该模拟
标签的行为。
Probably something like this:
References:
Google Chrome stylesheet: http://codesearch.google.com/codesearch#OAMlx_jo-ck/src/third_party/WebKit/Source/WebCore/css/html.css
Firefox stylesheet: http://mxr.mozilla.org/mozilla-central/source/layout/style/html.css
Why not to use the
<center>
tagAs a presentational tag, it makes very little sense to have to do something like:
Presentation should always be delegated to CSS when possible (i.e. almost always).
There are a variety of ways to "center" different things in different ways, but this should emulate the
<center>
tags behavior.使用
margin-left:auto;margin-right:auto;
Use
margin-left:auto;margin-right:auto;
在屏幕居中显示元素的一个快速技巧是使用负边距和绝对定位。
一个例子:
- 我们需要在屏幕居中显示一个 500x200 的 div
- html
这是内容
- CSS
.center { 宽度:500px;高度:200px;位置:绝对;顶部:50%;左:50%;左边距:-250px;顶部边距:-100px }
A quick trick to display elements centered on screen is using negative margin and absolute positioning.
An example:
- We need to display a div 500x200 centered on screen
- html
<div id='center'>this is the content</div>
- css
.center { width: 500px; height: 200px; position:absolute; top:50%; left:50%; margin-left: -250px; margin-top: -100px }
http://jsfiddle.net/BxyVb/
或者如果你也想按 y 轴居中,那么只需使用以百分比值表示的边距顶部,以便在小屏幕和大屏幕上都能看到
http://jsfiddle.net/BxyVb/
or if you want to center it by y axis too then just use a margin top in % value so it will be on sight on small and large screen