仅使用CSS做到完全居中的超级攻略

2020-05-05 07:44:07易采站长站整理

CSS Code复制内容到剪贴板

.Absolute-Center.is-Fixed {   
  position: fixed;   
  z-index: 999;   
}  

2015715155502404.jpg (373×290)

移动版Safari的说明:如果外面没有一层设置position: relative的容器,内容区会以整个文档的高度的中心点为基准居中,而不是以可视区域的高度中心点为基准居中。
  偏移值

  如果需要添加固定的标题,或者其他带偏移样式的元素,可以直接把类似top: 70px; 的样式写进内容区域的样式中。一旦声明了margin: auto; 的样式,内容块的top left bottom right的属性值也会同时计算进去。

  如果想让内容块在贴近侧边的过程中保持水平居中,可以使用right: 0; left: auto; 让内容贴在右侧,或者使用left: 0; right: auto; 使内容贴在左侧。

 

CSS Code复制内容到剪贴板

.Absolute-Center.is-Fixed {   
  position: fixed;   
  z-index: 999;   
}  

2015715155530004.jpg (608×401)

带响应式

  使用absolute的最大好处就是可以完美地使用带百分比的宽高样式!就算是min-width/max-width或者min-height/max-height也能够有如预期般的表现。

  再进一步加上padding样式的话,absolute式的完全居中也丝毫不会破坏!
 

CSS Code复制内容到剪贴板

.Absolute-Center.is-Responsive {   
  width: 60%;    
  height: 60%;   
  min-width: 200px;   
  max-width: 400px;   
  padding: 40px;   
}  

2015715155603781.jpg (608×402)

带溢出内容

  内容区高度大于可视区域或者一个position: relative的容器,其内容可能会溢出容器,或被容器截断。只要内容区域没有超出容器(没有给内容容器预留padding的话,可以设置max-height: 100%;的样式),那么容器内就会产生滚动条。
 

CSS Code复制内容到剪贴板

.Absolute-Center.is-Overflow {   
  overflow: <span style="width: auto; height: auto; float: none;" id="20_nwp"><a style="text-decoration: none;" mpid="20" target="_blank" href="http://cpro.baidu.com/cpro/ui/uijs.php?adclass=0&app_id=0&c=news&cf=1001&ch=0&di=128&fv=0&is_app=0&jk=f15759f1d844d7fd&k=auto&k0=auto&kdi0=0&luki=9&n=10&p=baidu&q=06011078_cpr&rb=0&rs=1&seller_id=1&sid=fdd744d8f15957f1&ssp2=1&stid=0&t=tpclicked3_hc&tu=u1922429&u=http%3A%2F%2Fwww%2Eadmin10000%2Ecom%2Fdocument%2F3058%2Ehtml&urlid=0" id="20_nwl"><span style="color:#0000ff;font-size:14px;width:auto;height:auto;float:none;">auto</span></a></span>;