CSS实现垂直水平居中有几种方法,哪种好
Admin 2022-07-13 群英技术资讯 1111 次浏览
这篇文章主要介绍“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进行举报,并提供相关证据,查实之后,将立刻删除涉嫌侵权内容。
猜你喜欢
真正意义上的inline-block水平呈现的元素间,换行显示或空格分隔的情况下会有间距,很简单的个例子:<input/><inputtype="submit"/>间距就来了~~我们使用CSS更改非inline-block水平元素为inline-block水平,也会有该问题:.spacea{display:inline-block;padding:.5em1em;background-color:#cad5eb;}<divclass="space"><ahre ...
这篇文章主要介绍了html table实现复杂表头的示例代码,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
css中调整a标签之间间距的方法1、css可以使用margin属性设置a标签间距,margin属性可以设置a标签的外边距,也可以使用如margin-left属性单独设置一个外边距。margin 简写属性在
这篇文章主要介绍了详解纯css实现瀑布流(multi-column多列及flex布局)的相关资料,用multi-column多列布局及flex布局实现瀑布流,感兴趣的小伙伴们可以参考一下
外边距折叠指的是毗邻的两个或多个外边距 (margin) 会合并成一个外边距,本文详细的介绍了一下css外边距折叠的实现,分为3种情况,非常具有实用价值,需要的朋友可以参考下
成为群英会员,开启智能安全云计算之旅
立即注册关注或联系群英网络
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