整理一下CSS元素居中对齐的方式,看看自己到底有多少货。
下面是要居中对齐的元素,代码如下
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>元素居中</title>
</head>
<body>
<div class="main">
<div></div>
</div>
</body>
</html>
flex
flex布局设置的是内部元素的位置,而不是自己本身的位置。
.main {
width: 200px;
height: 200px;
display: flex;
justify-content: center;
align-items: center;
background: tomato;
}
.main div{
width: 80px;
height: 80px;
background: turquoise;
}
position+margin
目标元素的Position属性必须是absolute,而其父元素的position是relative,(只要不是static即可)通过left,top,right,bottom的距离都是零,然后外边距自动对齐就OK了。目标元素必须有准确的width和height值。
.main {
width: 200px;
height: 200px;
position: relative;
background: tomato;
}
.main div{
width: 80px;
height: 80px;
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
margin: auto;
background: turquoise;
}
transform+position
目标元素的position属性是absolute,父元素的position属性为relative,相对于父元素距上方和左侧各50%,然后再向上和左移动自身的50%。
.main {
width: 200px;
height: 200px;
position: relative;
background: tomato;
}
.main div{
width: 80px;
height: 80px;
position: absolute;
left: 50%;
top: 50%;
right: 0;
transform: translate(-50%,-50%);
background: turquoise;
}
所有的方式只有如下这一种结果
文字的居中对齐也是挺常用的,这里也说一个简单的吧。
文字居中对齐
text-align为center时,文字水平居中;line-heigth和heigth等值时,文字垂直居中。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>元素居中</title>
<style>
.main {
width: 200px;
height: 200px;
display: flex;
justify-content: center;
align-items: center;
background: tomato;
}
.main p{
width: 80px;
height: 80px;
background: chartreuse;
text-align: center;
line-height: 80px;
}
</style>
</head>
<body>
<div class="main">
<p>居中文字</p>
</div>
</body>
</html>