120. 4 cool ways to center any items using CSS
1. Text Align
æåå± ä¸ï¼ä¸è¿ä¹åªæ¯é对æåã
1ï¼ testæåä¼æ¨ªåå± ä¸
2ï¼ å¯¹äºDiv ï¼ä¼å± ä¸å ¶ä¸æå
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
body{
margin: 0;
padding: 0;
background: #eaeaea;
}
.container{
width: 1000px;
height: 800px;
background: white;
margin: 0 auto;
text-align: center;
}
.box{
width:300px;
height:160px;
background: yellowgreen;
}
</style>
</head>
<body>
<div class="container">
test
<div class="box">test</div>
</div>
</body>
</html>
2. Margin Autoï¼
margin: 0 auto;
çä»·äºmargin-left:auto; margin-right:auto;
ä¸è¿°æ¹æ³æ¯å·¦å³å¯¹é½ï¼å¯¹äºä¸ä¸å¯¹é½ï¼éè¦è®¡ç®ä¸ä¸marginï¼å¹¶ä¸è®¾ç½®ç¶å ç´ ä¸ºoverflow:hidden
overflowï¼è¯¦è§£ overflowï¼è§£å³å¤è¾¹è·åå¡
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
body {
margin: 0;
padding: 0;
background: #eaeaea;
}
.container {
width: 1000px;
height: 600px;
background: white;
overflow: hidden;
}
.box {
width: 200px;
height: 200px;
background:deepskyblue;
margin:200px auto;
}
</style>
</head>
<body>
<div class="container">
<div class="box" ></div>
</div>
</body>
</html>
3. Display Flexï¼justify-content 主轴对é½æ¹å¼ align-items:侧轴对é½æ¹å¼
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
body{
margin:0;
padding:0;
background: #eaeaea;
}
.box1{
height:200px;
width:200px;
background: deepskyblue;
display: flex;
justify-content: center;
align-items: center;
}
.box2{
height:100px;
width:100px;
background: yellowgreen;
}
</style>
</head>
<body>
<div class="box1">
<div class="box2"></div>
</div>
</body>
</html>
4. Position Absolute
position:relativeç¨äºç¶å ç´ ï¼ position:absoluteç¨äºåå ç´ ï¼ åå ç´ ä¼ä¾ç §ç¶å±çè¾¹çè¿è¡å®ä½ç, ä¸ç¶position:absolute ä¼éå±åä¸å¯»æ¾è®¾ç½®äºposition:relativeçå ç´ è¾¹ç, ç´å°bodyå ç´ .
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
.box1 {
height: 200px;
width: 200px;
background: deepskyblue;
position: relative;
}
.box2 {
height: 100px;
width: 100px;
background: yellowgreen;
position: absolute;
top:50%;
left:50%;
transform: translate(-50%, -50%);
}
</style>
</head>
<body>
<div class="box1">
<div class="box2"></div>
</div>
</body>
</html>
上一篇: 前男友犯贱心理学:这5种表现并非真爱你