「这是我参与2022首次更文挑战的第11天,活动详情查看:2022首次更文挑战」
CSS笔记-元素居中
不同类型的元素居中方式略微有一些不同,这里记录的是 行内元素 和 块元素的 水平/垂直 居中。
相关行内元素及块元素的解析如下:
-
行内元素
-
设置宽高无效
-
margin只有左右有效。上下无效。
-
padding上下左右都有效,即 撑大内容空间
-
与其他元素在同一行
-
块元素
-
宽度与浏览器大小一致,与内容无关
-
独立占据一行
-
高度、内边距padding、外边距margin等都可设置
-
多个块元素排列时,依次从上到下展示
1. 水平居中
1.1 行内元素水平居中
这个是最简单的居中方式了,css 提供了 text-align 属性。直接设置值为 center ,就能实现在块元素内的行内元素的水平居中;
<body>
<span>行内元素水平居中</span>
</body>
<style>
body{
text-align: center;
border: 3px dashed red;
}
</style>
如下所示:
1.2 块元素水平居中
通过设置块元素的宽度width 以及 设置块元素的外边距margin-left、margin-right 为自适应 auto ;来实现块元素的水平居中。
<body>
<div>块元素水平居中</div>
</body>
<style>
body{
border: 3px dashed red;
}
div{
border: 1px solid;
width: 350px;
margin: 20px auto;
}
</style>
如下所示:
2.垂直居中
2.1 行内元素垂直居中
通过设置行内元素的高度与行高一致来实现行内元素的垂直居中。
<body>
<div>行内元素垂直居中</div>
</body>
<style>
div{
border: 1px solid;
width: 350px;
line-height: 200px;
height: 200px;
}
</style>
2.2 块元素垂直居中
2.2.1 高度固定
已知宽高的块元素 通过绝对定位的方式设置top 50% 和 margin-top 为高度的一半,则可完成垂直居中
<body>
<div>块元素-已知宽高 垂直居中</div>
</body>
<style>
body{
border: 3px dashed red;
height: 200px;
position: relative;
}
div{
border: 1px solid;
height: 50px;
position: absolute;
top: 50%;
margin-top: -25px;
}
</style>
2.2.2 高度未知
高度未知的块元素 ,通过css的transform属性来实现。
<body>
<div>块元素-已知宽高 垂直居中</div>
</body>
<style>
body{
border: 3px dashed red;
height: 200px;
position: relative;
}
div{
border: 1px solid;
position: absolute;
top: 50%;
transform: translateY(-50%);
}
</style>
以上,简单记录一下行内元素和块元素的两种居中方式。