有时候我们需要实现一个水平居中和垂直居中的效果。例如你想做一个网页版的PPT,你希望演示的内容区域总是居中。这里介绍一个纯css实现。
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>水平和垂直居中</title> <style type="text/css"> body { padding: 0; margin: 0; } #wrapper { width: 960px; margin: 10px auto; border: 1px solid #efefef; height: 600px; position: relative; } #content { width: 600px; height: 400px; position: absolute; left: 50%; top: 50%; margin: -200px 0px 0px -300px; border: 1px solid #343434; } </style> </head> <body> <div id="wrapper" class="clearfix"> <div id="content"> </div> </div> </body> </html>
居中的原理其实很简单。首先使用绝对定位,使得内容区域的坐上顶点位于父容器的中心点上,然后分别向左和向上移动自己高度和宽度的一半。其中的数学原理就是:
假设子容器居中,那么其左上角的顶点坐标为 [x,y] = [(父容器的宽度 - 子容器的宽度)/2,(父容器的高度 - 子容器的高度)/2]
我们可以显示的使用javascript这样定位,但是使用css我们让浏览器的渲染引擎帮我们做了这件事。