基本的HTML结构
<div class="parent"> <div class="child">DEMOdiv> div>
水平居中
一、inline-block、text-align:center
特点:适应性好,IE6、IE7不兼容inline-block。text-align:center会导致子元素的内容也居中。
<style> .parent{ text-align: center; } .child{ display: inline-block;/*宽度跟内容变化*/ } style>
二、table+margin
特点:只需要对子元素设置,IE6、IE7不支持table,
<style type="text/css"> .child{ display: table;/*宽度跟内容变化*/
margin: 0 auto; } style>
三、absolute+transform
特点:子元素不会影响其他元素,transform是CSS3内容,不兼容IE6、IE7、IE8。
<style type="text/css"> .parent{ position: relative; } .child{ position: absolute; left: 50%; transform: translateX(-50%);/*向左移自身宽度一半*/ } style>
四、flex+justify-content
特点:只对父容器设置,是CSS3内容,不兼容IE6、IE7、IE8。
<style type="text/css"> .parent{ display: flex; justify-content: center;/*设置了这个就用用设置子元素margin: 0 auto*/
}
.child{ margin: 0 auto;/*如果不用justify-content: center,可以用这个*/ }
style>
垂直居中
一、table-cell+vertical-align
要兼容IE7及以下,要更换为table结构
.parent{
display: table-cell;
vertical-align: middle;
}
二、absolute+transform
transform兼容性问题
.parent{
position: relative;
}
.child{
position: absolute;
top: 50%;
transform: translateY(-50%);
}
三、flex+align-items
flex、align-items兼容性问题
.parent{
display: flex;
align-items: center;
}
水平垂直居中
一、
.parent{width:200px;height:300px;}
.parent{
text-align: center;
display: table-cell;
vertical-align: middle;
}
.child{
display: inline-block;
}
二、
.parent{width:200px;height:300px;}
.parent{
position: relative;
}
.child{
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%,-50%);
}
三、
.parent{width:200px;height:300px;}
.parent{
display: flex;
justify-content: center;
align-items: center;
}