首页 > 开发 > CSS > 正文

让Div实现水平或垂直居中的相关方法

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

先来看一个最普通的实现示例:

创建一个新的html页面,

XML/HTML Code复制内容到剪贴板
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">   <html xmlns="http://www.w3.org/1999/xhtml">  
  2. <head>   <meta http-equiv="Content-Type" content="text/html; charset=gb2312" />  
  3. <title>无标题文档</title>   </head>  
  4. <body>   </body>  
  5. </html>  

在<head></head>中间,插入CSS代码

CSS Code复制内容到剪贴板
  1. #warp {     position: absolute;    
  2. width:500px;     height:200px;    
  3. left:50%;     top:370px;    
  4. margin-left:-250px;     margin-top:-100px;    
  5. }  

在HTML代码里调用这个CSS

CSS Code复制内容到剪贴板
  1. <div id="warp">      <span>共计</span>   
  2.     <span>71</span>      <span>条数据符合条件</span>   
  3. </div>  

显示如下:
201586183425378.png (500×48)

相关问题

这里让一个层居中是一个非常常见的布局方式,但在html中水平居中使用margin:0px auto;可以实现,但垂直居中使用外边距是无法达到效果的。(页面设置height:100%;是无效的),这里使用绝对定位+负外边距的方式来实现垂直居中,但同时要考虑页面重置大小的情况,需要使用js来修正。

1、让层水平居中

CSS Code复制内容到剪贴板
  1. .className{        width:270px;   
  2.     height:150px;        margin:0 auto;   
  3. }  

使用margin:0 auto;让层水平居中,留意宽度和高度必不可少。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表