方法一:
以前设置里面的绿div总是会使用{position:absolute;left:50%;top:50%;margin-left:-div宽度的一半;margin-top:-div高度的一半}。
这样比较麻烦,还需要自己计算高度和宽度,后来发现可以使用transform:translate(-50%,-50%);来代替margin,就能很好的解决了。
代码:
方法二:
.box4{ width:100px; height:100px; background:gray; position:relative;}.child4{ background:red; width:50px; height:50px; margin:auto; position:absolute; top:0; left:0; bottom:0; right:0;}
方法三:
.box1{ width:100px; height:100px; background:gray; text-align:center;/*居中效果只对文本内容和行内元素有效*/ display:table-cell; vertical-align:middle; } .child1{ display:inline-block; background:red; width:50px; height:50px; }
方法四:
.box2{ width:100px; height:100px; background:gray; display:table-cell; vertical-align:middle;}.child2{ margin:0 auto;/*在元素本身上设置,可以实现块级元素水平居中*/ background:red; width:50px; height:50px;}
方法五:
display:flex + margin:auto
.box2{ width:100px; height:100px; background:gray; display:flex;}.child2{ margin:auto; background:red; width:50px; height:50px;}