固定宽高的DIV绝对居中示例
看了一些代码,然后自己试验了一番,分享如下示例:
实现点: 如果元素的宽高固定,那么,css指定样式为top:50%;left:50%; 而margin-top和 margin-left 指定为负数,绝对值为自身宽高的一半
当然,position也需要指定为absolute,或者relative.
如果要在某个父级元素内居中,那么父元素也需要指定CSS的position属性。
如果有边框,那么,margin元素需要做一点微调。
代码如下:
<!DOCTYPE html><html> <head> <title> 固定宽高的元素居中示例 </title> <style>.content{width: 400px;height: 300px;position: absolute;left: 50%;top: 50%;margin-left: -200px;margin-top: -150px;background-color: #8888CC;} </style> </head> <body> <div class="content"><p>指定页面居中的元素</p> </div> </body></html>