使用CSS设置div水平居中
在CSS中,可以使用margin:0 auto
设置div水平居中。其中,auto就是左右自适应两边距离一样。
margin属性用于设置一个元素所有外边距的宽度,或者设置各边上外边距的宽度。
块级元素的垂直相邻外边距会合并,而行内元素实际上不占上下外边距。行内元素的的左右外边距不会合并。同样地,浮动元素的外边距也不会合并。允许指定负的外边距值,不过使用时要小心。
属性值:
auto
:浏览器计算外边距。length
:规定以具体单位计的外边距值,比如像素、厘米等。默认值是 0px。%
:规定基于父元素的宽度的百分比的外边距。
示例:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <style> .center { width: 300px; height: 200px; background-color: #009999; } .box { width: 100px; height: 100px; background-color: red; margin: 0 auto; } </style> </head> <body> <div class="center"> <div class="box"></div> </div> </body> </html>
效果图:
使用CSS设置div垂直居中
1、使用绝对定位和负外边距对块级元素进行垂直居中 (已知元素的高度)
如果我们知道元素的高度,可以这样来实现垂直居中:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>css div垂直居中</title> <style> .box{ width: 300px; height: 300px; background: #ddd; position: relative; } .child{ width: 150px; height: 100px; background: orange; position: absolute; top: 50%; margin: -50px 0 0 0; line-height: 100px; } </style> </head> <body> <div class="box"> <div class="child"></div> </div> </body> </html>
效果图:
这个方法兼容性不错,但是有一个小缺点:必须提前知道被居中块级元素的尺寸,否则无法准确实现垂直居中。
2、使用绝对定位和transform(未知元素高度)
如果我们不知道元素的高度,那么就需要先将元素定位到容器的中心位置,然后使用 transform 的 translate 属性,将元素的中心和父容器的中心重合,从而实现垂直居中:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>css 垂直居中</title> <style> .box{ width: 300px; height: 300px; background: #ddd; position: relative; } .child{ background: #93BC49; position: absolute; top: 50%; transform: translate(0, -50%); } </style> </head> <body> <div class="box"> <div class="child">css 垂直居中,css 垂直居中,css 垂直居中,css 垂直居中,css 垂直居中</div> </div> </body> </html>
效果图:
这种方法有一个非常明显的好处就是不必提前知道被居中元素的尺寸了,因为transform中translate偏移的百分比就是相对于元素自身的尺寸而言的。
3、使用flex布局
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>css div垂直居中</title> <style> .box{ width: 300px; height: 300px; background: #ddd; display: flex; flex-direction: column; justify-content: center; } .child{ width: 200px; height: 100px; background: #08BC67; line-height: 100px; } </style> </head> <body> <div class="box"> <div class="child"></div> </div> </body> </html>
效果图:
更多前端开发知识,请查阅 HTML中文网 !!
以上就是css如何设置div居中显示?的详细内容,更多请关注0133技术站其它相关文章!