1. 程式人生 > >css中幾個常用居中方法

css中幾個常用居中方法

1.拔河效應
水平居中:設定居中元素的left,right都為0,然後加一個margin:auto;即可。
舉個栗子:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
.container{
width: 400px;
height: 200px;
border:1px solid;
position: relative;
}
.main
{ width: 100px; height: 50px; background: blue; position: absolute; left: 0; right: 0; margin: auto; }
</style> </head> <body> <div class="container"> <div class="main"></div> </div> </body> </html>

方便記憶可以把margin:auto;理解為“開始拔河吧!”
垂直方向上的居中也是同理,只要設定top和bottom即可,上下左右居中的話那就全部寫上就ok啦

2.transform居中
直接放個栗子:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
.container{
width: 400px;
height: 200px;
border:1px solid;
position: relative;
}
.main{
width: 100px;
height: 50px;
background: blue;
position: absolute; left: 50%; transform: translate(-50% ,0); }
</style> </head> <body> <div class="container"> <div class="main"></div> </div> </body> </html>

首先給要居中元素設定left:50%; 居中元素就出現在父元素的中間處,
在這裡插入圖片描述
此時只要讓居中元素向左偏移自身的50%就達到居中效果了,此時可以用
transform: translate(-50% ,0);即可。上下居中也是同理。

3.felx佈局居中
也可以給父元素設定為彈性盒子display:flex; 然後設定主軸方向為居中對齊即可,(預設主軸為水平方向)舉個栗子:
父元素.container{

display:felx;
justify-content:center;
}
如果想要在垂直方向上居中,則先改變主軸方向為垂直flex-direction:column;
再設定justify-content:center;即可。(justify-content代表在主軸方向的對齊方式)

~自己學習過程記下的一些筆記,覺得有用就會分享出來,如有錯誤還請大神們指點!