CSS实现垂直水平居中有几种方法,哪种好
Admin 2022-07-13 群英技术资讯 454 次浏览
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进行举报,并提供相关证据,查实之后,将立刻删除涉嫌侵权内容。
猜你喜欢
CSS里collapse属性是干嘛的?CSS中的collapse其实是合并边框的意思,其使用语法是元素{border-collapse:collapse;}。下文给大家分享了具体的使用示例,对加深理解collapse属性会有帮助,感兴趣的朋友就继续往下看吧。
CSS进阶内容—浮动和定位详解我们在学习了CSS的基本知识和盒子之后,就该了解一下网页的整体构成了。CSS的三种布局流派网页布局的本质就是用CSS控制盒子的摆放来形成页面CSS提供了三种流派来控制盒子:普通流...
我们知道CSS的font属性是字体样式设置的一个属性,我们经常需要对字体样式进行操作,对此这篇就给大家来讲讲font属性的时候,以及使用需要注意的一些事项问题,文中的示例代码有一定的参考价值,有需要的朋友可以了解看看。
flex布局下图片不变形的方法是什么?一些朋友可能对flex布局比较熟悉,因为flex布局是比较常用的一个布局方式,虽然flex布局很好用,但是在使用flex布局也会存在一些问题,例如导致图片变形的情况,那么我们怎样才能让flex布局下的图片不变形的呢?下面给大家分享一个示例。
在css中,可以利用position属性把导航栏固定住,只需要给导航栏元素添加“position:fixed;”样式,将导航栏相对于浏览器窗口进行固定定位即可,这样被固定的导航栏元素就不会随着滚动条的拖动而改变位置。
成为群英会员,开启智能安全云计算之旅
立即注册Copyright © QY Network Company Ltd. All Rights Reserved. 2003-2020 群英 版权所有
增值电信经营许可证 : B1.B2-20140078 粤ICP备09006778号 域名注册商资质 粤 D3.1-20240008