本文收录css设置样式的一些小技巧
1. 设置文字在块级标签居中(包括水平居中和垂直居中)
水平居中
方法一:使用text-align
text-align:center
方法二:目标标签的父级标签设置position:relative,目标标签设置margin:auto
.parent { position: relative } .target { margin:auto }
垂直居中
设置line-height与父级元素height相同
div { 200px; height:40px; line-height:40px }
2. 块级元素在其父级元素内部居中
方法:利用绝对定位
步骤:(1)设置父级元素的position: relative(absolute也可以)
(2)设置目标元素的margin值为auto
(3)设置目标元素的left与right值相同,top与bottom值相同
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>元素居中</title> <style> .box1 { width: 50%; height: 300px; position: relative; background-color: #71b639; } .box2 { width: 200px; height: 200px; background-color: #ed6962; /*只设置设置auto只能达到水平居中的效果*/ /*margin: auto;*/ position: absolute; margin: auto; /*这里不一定要设置为0,只要对应的值相同即可*/ left: 0; right: 0; top: 500px; bottom: 500px; } </style> </head> <body> <div class="box1"> <div class="box2"></div> </div> </body> </html>
效果
3. 表格内文字垂直居中
<style>
.class {
vetical-align: middle
}
</style>
补充:vertical-align定义行内元素的基线相对于该元素所在行的基线的垂直对齐方式
top: 顶部对齐
middle: 居中对齐
bottom: 底部对齐
持续更新中...