div框如何居中

来源:互联网 发布:数据库接口类型有哪些 编辑:程序博客网 时间:2024/06/06 12:23

1:如果元素的宽高固定, 那么, css指定样式为top : 50 % ;left : 50 % ;

而margin - top和 margin - left 指定为负数,绝对值为自身宽高的一半 ;

参考实例如下:

< !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 >


2:如果我们的高度不固定呢?

这个时候用translate(x,y)就比较好了,x,y表示偏移量,可以用百分之几表示,例子如下

.white_content {display: none;position: absolute;top: 50%;left: 50%;height: auto;width: 500px;transform:translate(-50%,-50%);padding: 16px;border: 16px solid #52a3e2;background-color: white;z-index: 1002;overflow: auto;}



0 0
原创粉丝点击