水平居中
使用inline-block+text-align实现子模块在父模块中居中
例:.child{ display: inline-block; } .parent{ text-align: center; }
优点:兼容性比较好,能兼容IE6,7
使用table+margin
例:.child{ display: table; margin: 0 auto; }
优点:不需要设置父元素
使用absolute+transform
.parent{
position: relative;
}
.child{
position: absolute;
left: 50%;
transform: translateX(-50%);
}
优点:绝对定位脱离文档流,不会影响其他元素
使用flex+justify-content
.parent{
display: flex;
justify-content: center;
}
垂直居中
使用table-cell+vertical-align
.parent{
display: table-cell;
vertical-align: middle;
}
使用absolute+transform
.parent{
position: relative;
}
.child{
position: absolute;
top: 50%;
transform: translateY(-50%);
}
优点:绝对定位脱离文档流,不会影响其他元素
使用flex+align-items
.parent{
display: flex;
align-items: center;
}
水平,垂直都居中
结合以上。
如图所示,一个水平排列的列表,每项高度都未知,但要求底部对齐,有哪些方法可以解决呢?
方法1:
水平列表的底部对齐_方法1body{margin:0 auto;padding:0;}
ul{list-style-type:none;margin:0;padding:0;}
/*
父元素display:table-cell;vertical-align:bottom;
子元素display: inline-block;
*/
.list ul{display:table-cell;vertical-align:bottom;}
.list li{display:inline-block;width:100px;}
.list li.l1{background:#006699;height:200px;}
.list li.l2{background:#990000;height:150px;}
.list li.l3{background:#009900;height:100px;}
.list li.l4{background:#009999;height:180px;}
方法2:
水平列表的底部对齐_方法2body{margin:0 auto;padding:0;}
ul{list-style-type:none;margin:0;padding:0;}
/*
父元素position:relative;
子元素position:absolute;bottom:0;
*/
.list ul{position:relative;width:400px;height:200px;}
.list li{position:absolute;bottom:0;width:100px;}
.list li.l1{left:0;background:#006699;height:200px;}
.list li.l2{left:100px;background:#990000;height:150px;}
.list li.l3{left:200px;background:#009900;height:100px;}
.list li.l4{left:300px;background:#009999;height:180px;}
方法3:
水平列表的底部对齐_方法3body{margin:0 auto;padding:0;}
ul{list-style-type:none;margin:0;padding:0;}
/*
父元素display:flex;align-items:flex-end;
*/
.list ul{display:flex;align-items:flex-end;}
.list li{width:100px;}
.list li.l1{background:#006699;height:200px;}
.list li.l2{background:#990000;height:150px;}
.list li.l3{background:#009900;height:100px;}
.list li.l4{background:#009999;height:180px;}
一个幻灯片效果如图:
已知结构如下:
要求如下:幻灯(slide)宽高未知,指示器(pointer)在底部且水平居中,距离底部10px,指示器中的圆直径为10px,个数未知,背景为黑色,间距为5px,请完成CSS。
!DOCTYPE html>
幻灯布局*{padding:0;margin: 0;}
html,body{width: 100%;height: 100%;}
.slide{background-color: #9dc3e7;width: 75%;height: 38%;position: relative;}
.slide .pointer{position: absolute;bottom:10px;left: 50%;transform:translateX(-50%);}
.slide .pointer i{display: inline-block;width: 10px;height: 10px;border-radius:50%;background-color: #000;margin-right: 5px;}