在平常的写网页的过程中,居中是必不可少的一点,不同情况用不同的解决办法,会使写代码效率事半功倍,接下来我提供几种方法。
第一种:利用绝对定位
将position设置成absolute或fixed,这个视情况而定,然后将top和left设置成50%,但这时候并没有居中,因为移动50%并不是中心为参照,而是元素左上角为参考,所以此时元素处于页面中心的右下部分,只需要按照元素宽度和长度将margin设置为负的对应的一半。此方法优点:所有浏览器都支持,缺点:灵活性不强,必须知道长宽。代码和结果如下:
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>块级元素的居中</title>
</head>
<style>div{width: 400px;height: 200px;background:blueviolet ;position: absolute; /*这里可以改成fixed*/top: 50%;left: 50%;margin-top: -100px;margin-left: -200px;}
</style>
<body><div></div>
</body>
</html>
第二种:利用margin:auto
避免每次都计算长宽的一半,可以使用这种方法,margin设置为auto,top,botto,left,right都设置为0。将style里改成这样,结果与上图相同。但是这种在IE7和IE5不支持。
div{width: 400px;height: 200px;background:blueviolet ;position: absolute; /*这里可以改成fixed*/margin: auto;top: 0;left: 0;right: 0;bottom: 0;}
第三种:利用margin:0 auto
这种方法只能设置为水平居中,而且元素必须有宽度即margin:0 auto。
div{width: 120px;height: 120px;margin: 0 auto;background-color: blueviolet;}
第四种:利用display: table-cell ,vertical-align: middle
vertical-align这个属性会设置单元格框中的单元格内容的对齐方式。display设置为inline-block可以使元素变为表格元素
需要居中的元素display设置为inline-block,上一级text-align: center; vertical-align: middle;并且display设置为table-cell。
<style>.box{display: table-cell;width: 400px;height: 400px;text-align: center;vertical-align: middle;background-color: blueviolet;}.center{display: inline-block;width: 200px;height: 200px;background-color: red;}
</style>
<body><div class="box"><div class="center"></div></div>
</body>
第五种:利用text-align: center
这种方法可以让块级元素内部的文字水平居中,不能垂直居中。
div{width: 120px;height: 120px;text-align: center;background-color: blueviolet;}