让绝对定位的DIV绝对居中显示的方法

飘逸的风10年前 (2015-12-27)前端7190

         绝对居中:即在客户端上任何分辨率下纵横方向均居中

         

紫色的正方形为绝对定位的div

position:absolute; 
 top: 50%; 
 left: 50%; 只能把div定位在以红色圈为起点的位置,加上margin:-100px 0px 0px -100后,便可以让其移动到以红点为中心的位置。;

样例代码:

<html> 
<head> 
<title>Nice and Free CSS Template 11</title>
 
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> 
<style type="text/css"><!-- 
/*   body und schrift deffinitionen */ 
body { 
background-color: #e1ddd9; 
font-size: 12px; 
font-family: Verdana, Arial, Helvetica, SunSans-Regular, Sans-Serif; 
color:#564b47; 
padding:0px; 
margin:0px;
 
} 
#inhalt { 
position:absolute; 
height:200px; 
width:400px;
 
margin:-100px 0px 0px -200px; 
top: 50%; 
left: 50%;
 
text-align: left; 
padding: 0px; 
background-color: #f5f5f5; 
border: 1px dotted #000000; 
overflow: auto; 
} 
p, h1 { 
margin: 0px; 
padding: 10px; 

h1 { 
font-size: 11px; 
text-transform:uppercase; 
text-align: right; 
color: #564b47; 
background-color: #90897a; 

a { 
color: #ff66cc; 
font-size: 11px; 
background-color:transparent; 
text-decoration: none; 

--></style> 
</head> 
<body> 
<div id="inhalt">
 
<p><b>centered</b><br /><br /> 
This area should be horizontally and vertically centered.<br /> 
This text stays left aligned<br /> 
<b>ie mac doesn’t like this! </b><br /> 
<a href="/">more nice and free css templates</a> 
</p> 
<p> 
</div> 
</body> 
</html>

相关文章

escape()、encodeURI()、encodeURIComponent()区别详解

JavaScript中有三个可以对字符串编码的函数,分别是: escape,encodeURI,encodeURIComponent,相应3个解码函数:unescape,decodeURI,decod...

js判断undefined类型,undefined,null,NaN的区别

js判断undefined类型 今天使用showModalDialog打开页面,返回值时。当打开的页面点击关闭按钮或直接点浏览器上的关闭则返回值是undefined 所以自作聪明判断&nb...

JS设为首页加入收藏兼容特效

废话不多说,上代码: // 添加到收藏夹 function AddFavorite(sURL, sTitle) { try { if (typeof(sURL) == "undefi...

jquery简单代码实现复选框多选、单选、全不选功能,很实用

<html> <head>  <script type="text/javascript" src="https://code.jquery.com/jqu...

jQuery自适应宽度导航插件Horizo​​ntalNav

jQuery自适应宽度导航插件Horizo​​ntalNav

Horizo​​ntalNav 是一个 jQuery 导航插件,能够自适应容器的宽度。如果你曾经在一个项目中创建过这种效果,你就会知道,这是很难处理的。但这个插件很容易,并且支持 IE6、IE7。...

js 数组操作集合

注意:以下是按操作来分类的,有的方法有多个用途,就有重复 1、数组的创建 var arrayObj = new Array(); //创建一个数组 var arrayObj = new Arra...

发表评论

访客

看不清,换一张

◎欢迎参与讨论,请在这里发表您的看法和观点。