HTML 水平居中 垂直居中 垂直水平居中的几种实现方式

HTML 水平居中 垂直居中 垂直水平居中的几种实现方式水平居中方法一 在父容器上定义固定宽度 margin 值设成 auto lt DOCTYPEhtml gt lt html gt lt head gt lt metacharset utf 8 gt

水平居中

  1. 方法一:在父容器上定义固定宽度,margin值设成auto
 
   
   helloworld 
    
   
你好啊!!!!!!!!!

这里写图片描述

方法2:在子元素中将display设置为inline-block,父元素text-algin设置为center

 
   
   helloworld 
    
   
你好啊!!!!!!!!!

这里写图片描述

垂直居中

 
   
   helloworld 
    
   
你好啊!!!!!!!!!
 
   
   helloworld 
    
   
你好啊!!!!!!!!!

垂直水平居中

方式1:绝对定位

 
   
   居中 
    
   

这里写图片描述

方式二 定位+负margin

 
   
   居中 
    
   

这里写图片描述

方式3:使用translate实现平移

 下面的transform代码可以更换为transform: translate(-50%,-50%); 
 
   
   居中 
    
   

效果如上图。

方式4:通过设置bottom top left right margin来实现

 
   
   居中 
    
   

这里写图片描述

方式5:flex布局

最长使用,设置 display: flex;justify-content: center;align-items: center;三个属性; 
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>居中</title> <style> .father { 
    display: flex; justify-content: center; align-items: center; width: 500px; height: 500px; background-color: rgb(197, 34, 34); } .child { 
    width: 50px; height: 70px; background-color: rgb(36, 167, 64); } </style> </head> <body> <div class="father"> <div class="child"></div> </div> </body> </html> 

方式6:使用tablecell

<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>居中</title> <style> .father { 
    display: table-cell; vertical-align: middle; text-align: center; width: 500px; height: 500px; background-color: rgb(197, 34, 34); } .child { 
    display: inline-block; width: 50px; height: 70px; background-color: rgb(36, 167, 64); } </style> </head> <body> <div class="father"> <div class="child"></div> </div> </body> </html> 

方式7:JS方式

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <style> .father { 
    width: 500px; height: 500px; background-color: rgb(197, 34, 34); } .child { 
    width: 50px; height: 70px; background-color: rgb(28, 150, 123); } </style> <body> <div class="father"> <div class="child"> </div> </div> </body> <script> let father=document.getElementsByClassName('father')[0]; let child=document.getElementsByClassName('child')[0]; fatherH=father.clientHeight; fatherW=father.clientWidth; childW=child.offsetWidth; childH=child.offsetHeight; child.style.position="absolute"; child.style.top=(fatherH-childH)/2+'px'; child.style.left=(fatherW-childW)/2+'px'; </script> </html> 
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/204465.html原文链接:https://javaforall.net

(0)
上一篇 2026年3月19日 下午8:14
下一篇 2026年3月19日 下午8:14


相关推荐

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号