CSS实现垂直水平居中有几种方法,哪种好
Admin 2022-07-13 群英技术资讯 561 次浏览
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样式如上图所示先用标签选择器选择某个标签然后在elements区域就会自动找到该标签然后在右侧的styles区域整个区域都是该标签的样式,从上到下是显示的优先级,被划掉的Style就是说明是被另一个样式覆盖了把鼠标移动到style的样式上,会在每个样式上显示一个复选框,点击选中或者不选中就能本地调试样式还能自己手动在element.style{}里面写
css性能优化的解决办法:1、内联首屏关键CSS,性能优化有一个重要的指标,第一次有效绘制,内部CSS可以提前浏览器开始页面渲染。2、异步加载CSS。
本篇文章带大家了解一下CSS 变量,介绍下没人告诉你关于 CSS 变量的那些事。有一定的参考价值,有需要的朋友可以参考一下,希望对大家有所帮助。
这篇我们来了解CSS属性的内容,这里主要介绍字体属性、文本属性和列表属性的相关内容,下文对于这些属性都有很详细的介绍,对新手学习CSS有一定的帮助,需要的朋友可以参考了解。
在使用CSS3中rem属性过程中,我们经常拿来设置字体大小,或者做页面布局。那么,这些属性如何应用设置比较好呢?下文有实例供大家参考,对大家了解操作过程或相关知识有一定的帮助,而且实用性强,希望这篇文章能帮助大家,下面我们一起来了解看看吧。
成为群英会员,开启智能安全云计算之旅
立即注册Copyright © QY Network Company Ltd. All Rights Reserved. 2003-2020 群英 版权所有
增值电信经营许可证 : B1.B2-20140078 粤ICP备09006778号 域名注册商资质 粤 D3.1-20240008