示例8种(直接可用)"/>
水平垂直居中代码示例8种(直接可用)
- flex
- grid
- table-cell
- margin + transform
- absolute + transform
- absolute + -margin
- absolute + margin:auto
- inline-block + vertical-align
案例展示:
代码:(直接可用)
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title><style>/* 方法1:flex */.wrap{display: flex;justify-content: center;align-items: center;}/* 方法2:grid写法1 *//* .wrap{display: grid;}.box{align-self: center;justify-self: center;} *//* 方法2:grid写法2 *//*.wrap {display: grid;align-items: center;justify-items: center;}*//* 方法3:table-cell *//* .wrap{display: table-cell;text-align: center;vertical-align:middle} .box{display: inline-block;}*//* 方法4:margin + transform *//* .wrap{overflow:hidden}.box{margin: 50% auto;transform:translateY(-50%)} *//* 方法5:absolute + transform *//* .wrap{position: relative;}.box{position: absolute;left: 50%;top: 50%;transform: translate(-50%,-50%);} *//* 方法6:absolute + -margin *//* .wrap{position: relative;}.box{position: absolute;left: 50%;top: 50%;margin-left: -50px;margin-top: -50px;} *//* 方法7:absolute + margin:auto *//* .wrap{position: relative;}.box{position: absolute;left: 0;right: 0;top: 0;bottom: 0;margin: auto;} *//* 方法8:inline-block + vertical-align*//* .wrap{text-align: center;line-height: 300px; }.box{display: inline-block;vertical-align: middle;} */</style>
</head><body><div class="wrap" style="width: 300px;height: 300px;background-color: yellow;"><div class="box" style="width: 100px;height: 100px;background-color: pink;"></div></div>
</body></html>
代码学习来源视频:/?spm_id_from=333.788.videocard.0
更多推荐
水平垂直居中代码示例8种(直接可用)
发布评论