CSS实现垂直水平居中有几种方法,哪种好
Admin 2022-07-13 群英技术资讯 768 次浏览
这篇文章主要介绍“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进行举报,并提供相关证据,查实之后,将立刻删除涉嫌侵权内容。
猜你喜欢
父元素: 直接包含其他元素,这个元素就是包含元素的父元素。祖先元素:包含其他元素,这个元素就是包含元素的祖先元素。子元素: 直接被包含的元素。后代元素: 被包含的元素。
这篇文章主要介绍了html+css+js实现导航栏滚动渐变效果,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
本文将结合实例代码,介绍html实现弹窗的实例,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
用纯CSS怎样实现列表收起展开的效果?对列表的收起展开效果,大家应该常会简单,很多网站都会使用列表的收起展开效果做菜单,那么这样的效果究竟是怎样做的呢?下文有实现效果及代码,感兴趣的朋友可以了解看看。
css中clear属性的介绍:1、用于规定元素哪一侧不允许浮动元素,默认值为none,表示不清除,左右两侧允许浮动元素。2、确保当前元素的左右两侧没有浮动元素。clear只对元素本身的布局起作用。
成为群英会员,开启智能安全云计算之旅
立即注册Copyright © QY Network Company Ltd. All Rights Reserved. 2003-2020 群英 版权所有
增值电信经营许可证 : B1.B2-20140078 粤ICP备09006778号 域名注册商资质 粤 D3.1-20240008