首页 > 开发 > CSS > 正文

不固定宽度和高度的情况下CSS调整div居中的方法总结

2024-07-11 08:32:51
字体:
来源:转载
供稿:网友

很多新手在写css的时候经常遇到的一个问题,当div没有固定的宽度或者高度的时候,如何才能让div水平或者垂直居中显示。
如果div有固定宽度的话,用padding,margin都很容易实现。方法有很多种。不过经常遇到这种div没有固定的宽度高度的情况,我们就不能用margin,padding设置固定的距离了。这个问题让很多人头疼。而怎么样才能让这个div居中显示呢?其实这种情况解决的办法也是有很多种,js,css都可以实现。
这里主要介绍一下采用css的方法,有什么问题还请各位看官指出。

方法一:
用一个“ghost”伪元素(看不见的伪元素)和 inline-block / vertical-align 可以搞定居中,非常巧妙。但是这个方法要求待居中的元素是 inline-block,不是一个真正通用的方案。
html如下:

XML/HTML Code复制内容到剪贴板
  1. <div class="block" style="height: 300px;">       <div class="centered">  
  2.         <h1>haorooms案例题目</h1>           <p>haorooms案例内容,haorooms案例内容haorooms案例内容haorooms案例内容haorooms案例内容haorooms案例内容haorooms案例内容haorooms案例内容haorooms案例内容</p>  
  3.     </div>   </div>  

css如下:

CSS Code复制内容到剪贴板
  1. /* This parent can be any width and height */   .block {   
  2.   text-align: center;    }   
  3. /* The ghost, nudged to maintain perfect centering */   .block:before {   
  4.   content: '';      display: inline-block;   
  5.   height: 100%;      vertical-align: middle;   
  6.   margin-right: -0.25em; /* Adjusts for spacing */   }   
  7. /* The element to be centered, can      also be of any width and height */    
  8. .centered {      display: inline-block;   
  9.   vertical-align: middle;      width: 50%;   
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表