CSS实现垂直水平居中有几种方法,哪种好
Admin 2022-07-13 群英技术资讯 816 次浏览
这篇文章主要介绍“CSS实现垂直水平居中有几种方法,哪种好”,有一些人在CSS实现垂直水平居中有几种方法,哪种好的问题上存在疑惑,接下来小编就给大家来介绍一下相关的内容,希望对大家解答有帮助,有这个方面学习需要的朋友就继续往下看吧。CSS 居中对齐
flex 居中
优点:可对未知高度进行居中处理
<style>
.wrap{height: 100%;display: flex; justify-content: center; align-items: center;align-content:center;}
.other{background-color: #ccc; width: 400px;height: 400px;} /* 额外的样式 可去除 */
</style>
<div class="wrap">
<div class="other">
<h2>这是第二层的内容 不会居中</h2>
</div>
</div>
position + translate 居中
优点: 可对未知高度进行居中处理、嵌套层最少
<style>
/* position 可选 absolute|fixed*/
.center{position: absolute;left: 50%;top: 50%; transform: translate(-50%,-50%);}
.other{background-color: #ccc; } /* 额外的样式 可去除 */
</style>
<div class="center other">
<h2>这一层的内容 不会居中</h2>
</div>
table-cell 居中
缺点:1. 居中层需要设置宽度(.center)。 2.外层多嵌套一层(.cell) 3. 居中层必须设置宽度(允许 %)
<style>
.wrap{display: table;width: 100%;height: 100%;}
.cell{display: table-cell;vertical-align:middle;}
.center{width: 400px;margin-left:auto;margin-right:auto;}
.other{background-color: #ccc; height: 400px;} /* 额外的样式 可去除 */
</style>
<div class="wrap">
<div class="cell">
<div class="center other">
<h2>这一层的内容 不会居中</h2>
</div>
</div>
</div>
传统居中 (2种)
缺点:1. margin 值必须为auto。 2. 居中层必须设置高宽(允许 %) 3. 必须使用 position
<style>
/*
1. left、top、right、bottom 可以任意,但必须相等
2. position 可选 absolute|fixed
*/
.center{position: absolute;left: 10px;top: 10px;right: 10px;bottom: 10px;margin: auto;width: 400px;height: 400px;}
.other{background-color: #ccc; } /* 额外的样式 可去除 */
</style>
<div class="center other">
<h2>这一层的内容 不会居中</h2>
</div>
缺点: 居中层必须设置固定高宽,并且magin需要通过高宽计算得出。
<style>
.wrap{position: relative;height: 100%;}
.center{position: absolute;left: 50%;top: 50%; width: 400px;height: 300px; margin-left: -200px;margin-top: -150px;}
.other{background-color: #ccc; } /* 额外的样式 可去除 */
</style>
<div class="wrap">
<div class="center other">
<h2>这一层的内容 不会居中</h2>
</div>
</div>
总结
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:mmqy2019@163.com进行举报,并提供相关证据,查实之后,将立刻删除涉嫌侵权内容。
猜你喜欢
方法:1、用animation属性给元素绑定动画;2、用“@keyframes 名称{100%{transform:rotate(旋转角度)translate(位移距离);}}”语句设置元素的旋转和位移的动作关键帧,实现旋转加位移动画效果。
这篇文章主要介绍了canvas画图被放大且模糊的解决方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
我们在网上做题目的时候,如果题目一起随选项滑动,那么就需要来回翻看题目,这样的体验效果是很差的。因此,这篇文章就给大家介绍用CSS sticky布局来实现题目定位顶部的效果,本文有思路以及代码,感兴趣的朋友一起来了解一下吧。
CSS盒子塌陷怎么办?CSS盒子塌陷也就是指本应该在父盒子内部的元素跑到了外部。那么究竟为何出现这样的问题呢?我们该怎样解决处理?对此本文就给大家分享了五种解决CSS盒子塌陷的方法技巧,有需要的朋友可以参考。
CSS中focus-within用法是什么,哪些场景用?有不少朋友对此感兴趣,下面小编给大家整理和分享了相关知识和资料,易于大家学习和理解,有需要的朋友可以借鉴参考,下面我们一起来了解一下吧。
成为群英会员,开启智能安全云计算之旅
立即注册关注或联系群英网络
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备09006778号 域名注册商资质 粤 D3.1-20240008