水平居中(margin:0 auto;)
关于这个,大家应该是最不陌生的,不管是在培训班还是自己自学的话 。这个应该是老师讲的第一个方法了(水平方向上),但是其有一个前提,就是被包裹的元素不能有浮动的属性。否则的话这个属性就会失效。具体如下图代码:
<style>
body{margin: 0;}
.box{
width: 400px;
height: 400px;
border:1px solid red;
}
item{
margin:0 auto;
width: 100px;
height: 100x;
background: green;
}
</style>
<body>
<div class="box">
<div class="item"></div>
</div>
</body>
水平垂直居中: 子元素相对于父元素绝对定位,并且margin值位auto
* {
margin: 0;
padding: 0;
}
.box {
position: relative;
margin: 0 auto;
height: 400px;
width: 400px;
background-color: #00FF00;
}
.children {
position: absolute;
right: 0px;
top: 0px;
bottom: 0px;
margin: auto 0;
height: 100px;
width: 100px;
background-color: #FF00FF;
}
<div class="box">
<div class="children"></div>
</div>
水平居中(text-align:center;)
这个属性在没有浮动的情况下,我们可以将其转换为inline/inline-block,然后其父元素加上text-align:center;属性就可以将其居中
<style>
body{margin: 0;}
.box{
width: 400px;
height: 400px;
border:1px solid red;
text-align:center;
}
item{
display:inline/inline-block;
width: 100px;
height: 100x;
background: green;
}
</style>
<body>
<div class="box">
<div class="item"></div>
</div>
</body>
flex布局
* {
margin: 0;
padding: 0;
}
.box {
display: flex;
justify-content: flex-end;
align-items: center;
height: 400px;
width: 400px;
background-color: #00FF00;
}
.children {
height: 100px;
width: 100px;
background-color: #FF00FF;
}
<div class="box">
<div class="children"></div>
</div>