块级元素居中
1.div使用绝对布局,设置margin:auto;并设置top、left、right、bottom的值相等即可,不一定要都是0。
css代码:
<style>
.main{
width: 200px;
height: 200px;
background-color: red;
position: absolute;
margin: auto;
top: 0;
left: 0;
bottom: 0;
right: 0;
}
</style>
HTML代码:
<div class="main"></div>
2.仍然是绝对布局,让left和top都是50%,这在水平方向上让div的最左与屏幕的最左相距50%,垂直方向上一样,所以再用transform向左(上)平移它自己宽度(高度)的50%,也就达到居中效果了。
.main{
width: 200px;
height: 200px;
background-color: red;
position: absolute;
margin: auto;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
}
3.使用flex布局,父元素给定宽高:
css样式:
.box {
background-color: #FF8C00;
width: 300px;
height: 300px;
display: flex;
justify-content: center;
align-items: center;
}
.content {
background-color: #F00;
width: 100px;
height: 100px;
}
HTML样式:
<div class="box">
<div class="content"> </div>
</div>
4.还有一种方法,就是display:table;可自行学习;
文本居中
文本居中比较简单,以下是几种常见的方法:
1.第一种就来flex吧,其实和前面一样,代码不用修改就能直接用:
css样式
.box {
background-color: #FF8C00;
width: 300px;
height: 300px;
display: flex;
justify-content: center;
align-items: center;
}
html样式
<div class="box">
你好
</div>
2.第二种就选line-height属性吧,代码:
css样式
.box {
background-color: #FF8C00;
width: 300px;
height: 300px;
text-align: center;
line-height: 300px;
}
html样式和第一种一样;这种是最常用的文本居中;
3.第三种和第二种有点相似,我们依然使用text-align属性,但垂直居中我们使用vertical-align:middle;这个属性有点特殊,因为它只能作用在inline-block或者inline,还有table-cell等元素内;
.box {
background-color: #FF8C00;
width: 300px;
height: 300px;
text-align: center;
vertical-align: middle;
display: table-cell;
}
4.可以将文本放在一个行内元素中,然后为该行内元素添加属性display:block;;之后就和块元素一样使用定位布局;
若还有什么好的布局方法,请不吝赐教!!!