html中div水平居中(垂直居中的多种方式)

来源:国外服务器 在您之前已被浏览:1 次
导读:目前正在解读《html中div水平居中(垂直居中的多种方式)》的相关信息,《html中div水平居中(垂直居中的多种方式)》是由用户自行发布的知识型内容!下面请观看由(国外主机 - www.2bp.net)用户发布《html中div水平居中(垂直居中的多种方式)》的详细说明。
笨笨网美国主机,w ww.2 b p .n e t

马上又要到秋招的时候了,又有不少人打算换工作了。前端在面试中总会被问到的一道基础题div居中方法,这里给大家总结一下都有哪些常用的方法。

绝对定位

  • 父级元素(parent)采用相对定位(relative),需要居中的元素(demo)采用绝对定位(absolute)。
  • 居中元素向上偏移50%,向左偏移50%,此时左顶点位于中心,不过我们需要的是整体居中,所以在偏移自身一半的宽高。(如下图)

html中div水平居中(垂直居中的多种方式)

还未偏移一半自身宽高

<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布局等。

笨笨网美国主机,w ww.2 b p .n e t
提醒:《html中div水平居中(垂直居中的多种方式)》最后刷新时间 2025-03-21 11:17:30,本站为公益型个人网站,仅供个人学习和记录信息,不进行任何商业性质的盈利。如果内容、图片资源失效或内容涉及侵权,请反馈至,我们会及时处理。本站只保证内容的可读性,无法保证真实性,《html中div水平居中(垂直居中的多种方式)》该内容的真实性请自行鉴别。