前端学习笔记(一)
如何通过css布局实现水平垂直居中
通过display:table-cell以及相关的css代码实现水平垂直居中
<!DOCTYPE html><html>
<head>
<meta charset="utf-8">
<title>测试</title>
<style>
#box1{ width:300px; height:300px; border:1px solid red; display: table-cell; text-align:center;/*将元素下面的内联元素设置为居中显示*/
vertical-align: middle;/*定义行内元素相对于该元素所在的行垂直对齐*/
/*由于之前设置了display:table-cell;所以vertical-align:middle;才能起作用*/
}
#box2{ width:100px; height:100px; border:1px solid grey; display: inline-block;/*将要垂直居中的设置为行内块*/
vertical-align: middle; text-align:center; line-height: 100px; }
</style>
</head>
<body>
<div id="box1">
<div id="box2">
水平垂直居中 </div>
</div>
</body></html>
通过flex布局实现水平垂直居中
<!DOCTYPE html><html>
<head>
<meta charset="utf-8">
<title>测试</title>
<style>
#box1{ width:300px; height:300px; border:1px solid red; /*下面三行是实现flex布局实现水平垂直居中的关键代码*/
display:flex;/*设置为flex布局*/
justify-content: center;/*属性定义项目在主轴上的对齐方式为居中对齐*/
align-items: center;/*属性定义项目在交叉轴上居中对齐*/
}
#box2{ width:100px; height:100px; border:1px solid grey; text-align:center; line-height: 100px; }
</style>
</head>
<body>
<div id="box1">
<div id="box2">
水平垂直居中 </div>
</div>
</body></html>
通过绝对定位实现水平垂直居中
<!DOCTYPE html><html>
<head>
<meta charset="utf-8">
<title>测试</title>
<style>
#box1{ width:300px; height:300px; border:1px solid red; position:relative; }
#box2{ width:100px; height:100px; border:1px solid grey; position: absolute; text-align:center; line-height: 100px; left:50%; top:50%; transform:translate(-50%,-50%);/*往上x轴往左y轴移动自身长度的50%,使其居中*/
}
</style>
</head>
<body>
<div id="box1">
<div id="box2">
水平垂直居中 </div>
</div>
</body></html>