css如何让盒子水平垂直居中?教你八个方法
Admin 2021-09-29 群英技术资讯 1330 次浏览
今天给大家分享的是css让盒子水平垂直居中的方法,本文提供了八种盒子水平垂直居中方法及示例供大家参考,对新手学习和理解css水平垂直居中盒子有一定的帮助,感兴趣的朋友接下来跟随小编一起看看吧。
原始代码:
center.html:
<!DOCTYPE html>
<html lang="Zh">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Center</title>
<link rel="stylesheet" href="center.css">
</head>
<body>
<div class="father">
<div class="son"></div>
</div>
</body>
</html>
center.css:
body {
background-color: #6ed0ff;
}
.father {
background-color: #be33ec;
border-radius: 20px;
box-shadow: 0 0 15px rgb(0, 0, 0);
margin: 100px auto;
width: 300px;
height: 300px;
}
.son {
background-color: #fcff00;
border-radius: 20px;
box-shadow: 0 0 10px rgb(0, 0, 0);
width: 100px;
height: 100px;
}
原始效果:

实现子盒子相对于父盒子垂直居中效果:

1. grid
.father {
display: grid;
}
.son {
align-self: center;
justify-self: center;
}
2. absolute + 负margin
.father {
position: relative;
}
.son {
position: absolute;
left: 50%;
top: 50%;
margin-left: -50px;
margin-top: -50px;
}
3. absolute + transform
.father {
position: relative;
}
.son {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
4. absolute + margin: auto
.father {
position: relative;
}
.son {
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
margin: auto;
}
5. flex
.father {
display: flex;
justify-content: center;
align-items: center;
}
6. margin+transfrom
.father {
overflow: hidden;
}
.son {
margin: 50% auto;
transform: translateY(-50%);
}
7. table-cell
.father {
display: table-cell;
text-align: center;
vertical-align: middle;
}
.son {
display: inline-block;
}
8. inline-block + vertical-align
.father {
text-align: center;
line-height: 300px;
}
.son {
display: inline-block;
vertical-align: middle;
}
以上就是css实现水平垂直居中盒子的八种方法啦,有需要的朋友可以借鉴参考,希望对大家学习CSS有帮助,想要了解更多从CSS的使用,大家可以继续浏览群英网络其他相关的文章。
文本转载自脚本之家
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:mmqy2019@163.com进行举报,并提供相关证据,查实之后,将立刻删除涉嫌侵权内容。
猜你喜欢
这篇文章主要介绍了css简单动画之transition属性详解,需要的朋友可以参考下
实现这个效果想利用 CSS 完全复制是比较困难的。CSS 模拟出来的光效阴影相对会 Low 一点,只能说是尽量还原。其实每组光都基本是一样的,所以我们只需要实现其中一组,就几乎能实
在实际的项目中,为了美观效果,经常会隐藏滚动条,但是依然是可以实现滚动的。这篇我们主要来了解不同浏览器中隐藏滚动条的方法,文中介绍了Firefox浏览、IE浏览和Chrome和Safari浏览器等常见浏览器的设置方法,感兴趣的朋友就继续往下看吧。
目录背景粘性定位:案例:实现的代码问题探索及项目中的坑背景最近在做项目迁移,因为技术不同,导致某些功能的问题需要手动解决;如何在居位在主体区域底部不随内容而滚动;<br /> OK进入正
如何理解div水平居中呢?这样想象就好了,在一个长方形的div上,水平划一条直线,然后取水平线的中间点,这就是div水平居中了,div水平居中也叫div左右居中,如图所示。 div水平居中的例子如下所示。 divstyle=width:150px;height:80px;border:1pxsolidreddi
成为群英会员,开启智能安全云计算之旅
立即注册关注或联系群英网络
7x24小时售前:400-678-4567
7x24小时售后:0668-2555666
24小时QQ客服
群英微信公众号
CNNIC域名投诉举报处理平台
服务电话:010-58813000
服务邮箱:service@cnnic.cn
投诉与建议:0668-2555555
Copyright © QY Network Company Ltd. All Rights Reserved. 2003-2020 群英 版权所有
增值电信经营许可证 : B1.B2-20140078 ICP核准(ICP备案)粤ICP备09006778号 域名注册商资质 粤 D3.1-20240008