发布于 2016-03-10 02:18:14 | 242 次阅读 | 评论: 0 | 来源: 分享
CSS层叠样式表
CSS(层叠样式表) 即 级联样式表 。
它是一种用来表现HTML(标准通用标记语言的一个应用)或XML(标准通用标记语言的一个子集)等文件样式的计算机语言。
在前端开发过程中,盒子居中是常常用到的。其中 ,居中又可以分为水平居中和垂直居中。水平居中是比较容易的,直接设置元素的margin: 0 auto就可以实现。但是垂直居中相对来说是比较复杂一些的。下面我们一起来讨论一下实现垂直居中的方法。
首先,定义一个需要垂直居中的div元素,他的宽度和高度均为300px,背景色为橙色。代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>index</title>
<style>
.content {
width: 300px;
height: 300px;
background: orange;
}
</style>
</head>
<body>
<div class="content"></div>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>index</title>
<style>
.content {
width: 300px;
height: 300px;
background: orange;
margin: 0 auto;
}
</style>
</head>
<body>
<div class="content"></div>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>index</title>
<style>
html, body {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
}
.content {
width: 300px;
height: 300px;
background: orange;
margin: 0 auto; /*水平居中*/
}
</style>
</head>
<body>
<div class="content"></div>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>index</title>
<style>
html, body {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
}
.content {
width: 300px;
height: 300px;
background: orange;
margin: 0 auto; /*水平居中*/
position: relative; /*脱离文档流*/
}
</style>
</head>
<body>
<div class="content"></div>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>index</title>
<style>
html,body {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
}
.content {
width: 300px;
height: 300px;
background: orange;
margin: 0 auto; /*水平居中*/
position: relative; /*脱离文档流*/
top: 50%; /*偏移*/
}
</style>
</head>
<body>
<div class="content"></div>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>index</title>
<style>
html,body {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
}
.content {
width: 300px;
height: 300px;
background: orange;
margin: 0 auto; /*水平居中*/
position: relative; /*脱离文档流*/
top: 50%; /*偏移*/
margin-top: -150px;
}
</style>
</head>
<body>
<div class="content"></div>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>index</title>
<style>
html,body {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
}
.content {
width: 300px;
height: 300px;
background: orange;
margin: 0 auto; /*水平居中*/
position: relative; /*脱离文档流*/
top: 50%; /*偏移*/
transform: translateY(-50%);
}
</style>
</head>
<body>
<div class="content"></div>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>index</title>
<style>
html,body {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
}
body {
display: flex;
align-items: center; /*定义body的元素垂直居中*/
justify-content: center; /*定义body的里的元素水平居中*/
}
.content {
width: 300px;
height: 300px;
background: orange;
}
</style>
</head>
<body>
<div class="content"></div>
</body>
</html>