html中div水平居中(垂直居中的多种方式)
马上又要到秋招的时候了,又有不少人打算换工作了。前端在面试中总会被问到的一道基础题div居中方法,这里给大家总结一下都有哪些常用的方法。定位父级元素(parent)采用相对定位(relative),需要居中的元素(demo)采用定位(absolute)。居中元素向上偏移50%,向左偏移50%,此时左顶点位于中心,不过我们需要的是整体居中,所以在偏移自身一半的宽高。(如下图)还未偏移一半自身宽高<style> .parent { position: relative; width: 500px; height: 500px; border: solid red 1px; } .demo { position: absolute; width: 100px; height: 100px; border: solid blue 1px; top: 50%; left: 50%; margin-top: -50px; margin-left: -50px; } </style> <body> <div class="parent"> <div class="demo"></div> </div> </body>弹性方法居中通过flex弹性布局设置垂直居中和水平居中 <style> .parent { width: 500px; height: 500px; border: solid red 1px; display: flex; // 垂直,水平居中 align-items: center; justify-content: center; } .demo { width: 100px; height: 100px; border: solid blue 1px; } </style> <body> <div class="parent"> <div class="demo"></div> </div> </body>使用transform居中在子元素不知道自身宽高情况,使用transform进行比偏移。 <style> .parent { position: relative; width: 500px; height: 500px; border: solid red 1px; } .demo { position: absolute; border: solid blue 1px; top: 50%; left: 50%; transform: translate(-50%, -50%); } </style> <body> <div class="parent"> <div class="demo">居中</div> </div> </body>以上3种是常用的方法,当然还有其他居中方法比如grid布局,table-cell布局等。
- 随机文章
- 核心危机(核心危机魔石合成攻略)
- 饿了么红包怎么用(饿了么红包怎么用微信支付)
- 儿童教育文章(儿童教育)
- 光遇花手先祖位置(安卓光遇手花先祖)
- 广州4a广告公司(广州4a广告公司创意总监年薪)
- 抖音卡(抖音卡顿怎么解决)
- xboxones(xboxone手柄怎么配对主机)
- 陈武简历
- 鬼泣5攻略(鬼泣5攻略第三关怎么跳)
- 地球日主题(2020年世界地球日主题)
- 冰客(冰客果汁)
- yy魔兽(yy魔兽世界)
- 国外成人游戏(国外成人游戏注册需要visa信用卡)
- 充值卡代理(充值卡代理加盟)
- 郭妮小说(恶魔的法则郭妮小说)
- 东天目山(东天目山景区)
- 杭同(杭同培训中心怎么样)
- 蝙蝠给人类的一封信(蝙蝠给人类的一封信)
- 大松电饭煲(美的大松电饭煲)
- 疯狂填字(疯狂填字5)
- 点对点短信息(点对点短信息费是什么意思)
- 观音普门品(观音普门品念诵全文)
- 河北省大运会(河北省大运会时间)
- 哈利波特官网(哈利波特官网在哪里)
- 骇客神条(骇客神条怎么辨别真假)
- 杜星霖(杜星霖图片)
- 查传倜(查传倜个人生活)
- 广州晓港公园(广州晓港公园正门图片)
- 钢筋等级符号(钢筋等级符号电脑怎么输入)
- 常州天宁寺(常州天宁寺求什么灵验)
