让一个小盒子(child)在大盒子(parent)中垂直水平都居中
效果图:
HTML:
<div class="parent"> <div class="child"></div> </div>
CSS:
方法1:父:position: relative;子position: absolute;top: 0;left: 0;bottom: 0;right: 0;(不推荐)
.parent{ width: 800px; height: 500px; border: 2px solid #000; position: relative; background: mediumaquamarine; margin: 0 auto; } .child{ width: 200px; height: 200px; margin: auto; position: absolute; top: 0; left: 0; bottom: 0; right: 0; background: magenta; }
方法2: 父:position: relative;子:position: absolute;top:50%;left: 50%;transform: translate(-50%,-50%);
.parent{ width: 800px; height: 500px; border: 2px solid #000; background: aqua; position: relative; } .child{ width: 200px; height: 200px; background: magenta; position: absolute; left: 50%; top: 50%; transform: translate(-50%,-50%); }
方法3: 父:display: table-cell;vertical-align: middle;text-align: center;子:display: inline-block;
.parent{ width: 800px; height: 500px; border: 2px solid #000; display: table-cell; vertical-align: middle; text-align: center; background: mediumaquamarine; } .child{ width: 200px; height: 200px; display: inline-block; background: magenta; }
方法4:父:display:flex;justify-content:center;align-items:center;
.parent{ width: 800px; height: 500px; border: 2px solid #000; background: aqua; display:flex; justify-content:center; align-items:center; } .child{ width: 200px; height: 200px; background: magenta; }
方法5:父:display:flex;justify-content:center; 子:align-self:center;
.parent{ width: 800px; height: 500px; border: 2px solid #000; background: aqua; display:flex; justify-content:center; } .child{ width: 200px; height: 200px; background: magenta; align-self:center; }
方法6:父:display: box;display: -webkit-box;-webkit-box-align: center;-webkit-box-pack: center;
.parent{ width: 800px; height: 500px; border: 2px solid #000; background: aqua; display: box; display: -webkit-box; -webkit-box-align: center; -webkit-box-pack: center; } .child{ width: 200px; height: 200px; background: magenta; }
方法7:
.parent{ width: 800px; height: 500px; border: 2px solid #000; background: aqua; position: relative; } .child{ width: 300px; height: 200px; background: magenta; position: absolute; /*设定水平和垂直偏移父元素的50%,再根据实际长度将子元素上左挪回一半大小*/ left: 50%; top: 50%; margin-left: -150px; margin-top: -100px; }
方法8:在窗口中垂直居中定位
div{ width:500px; height:500px; position:fixed; left:50%; margin-left:-250px; /* 负的宽度的一半*/ top:50%; margin-top:-250px; /* 负的高度的一半*/ }
方法9:让图片在一个盒子里垂直居中(在img后边添加一个span元素):
img{ vertical-align: middle;} span{ vertical-align: middle; display: inline-block; width: 0px; height: 100%; }