浏览:2772008-04-24 18:17   来自looping      :


  有两个DIV,怎么让第二个DIV在第一个DIV中水平和垂直居中。
1。DIV1高度和宽度是固定的。
2.DIV2的高度和宽度未知,随其内容自适应。
3。实现效果,让DIV2在DIV1中居中(包括水平和垂直)
4.no script

谢谢~

楼主
  3周前   杨正祎(阿一)      :
水平居中没有什么好说的。
垂直居中,没有什么特别完美的办法,下面供你参考——

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>div里面图片垂直居中的几个例子</title>
<style type="text/css">
<!--
* {
margin: 0;
padding: 0;
}
/*FireFox ok!
.a {
width: 500px;
height: 500px;
border: 1px solid #666;
display: table-cell;
text-align: center;
vertical-align: middle;
}*/
/*for IE*/
.a {
width: 500px;
height: 500px;
border: 1px solid #666;
overflow: hidden;
position: relative;
text-align: center;
}

.a .b {
position: absolute;
top: 50%;
}
img {
position: relative;
top: -50%;
left: -50%;
}
-->
</style>
</head>

<body>

<div class="a">
<div class="b"><img src="logo.gif" /></div>
</div>

</body>

</html>
回复  1楼 回到顶楼 
  3周前   looping      :
@杨正祎(阿一)
我赋值代码到本地,IE6.0中什么都看不到,safari和ff3.0中图片太靠左边,有一半没露出来。
回复  2楼 回到顶楼 
  3周前   刚刚      :
如果不用JavaScript,那么最终效果只有两种方案:
1、div2的宽和高固定:

<div id="div1" style="border-right: thin solid; border-top: thin solid; border-left: thin solid; border-bottom: thin solid; left: 50px; width: 200px; position: absolute; top: 50px; height: 300px;">
<div id="div2" style="border-right: thin dashed; border-top: thin dashed; border-left: thin dashed; border-bottom: thin dashed; left: 50%; width: 100px; position: absolute; top: 50%; height: 100px; margin-left:-50px; margin-top:-50px;">div2在div1中水平方向和垂直方向居中
</div>
</div>
原理很简单:将left和top设置为50%来定位div到浏览器中央,再将margin-left和margin-top值设置为宽和高的一半,使div居中显示。(参考网页地址:http://tech.idv2.com/2007/07/22/center-div-horizontally-and-vertically-with-css/

如果div2的宽和高是不确定的,那么就必须用的JavaScript,随时取得div2变化的宽和高中之值,用来改变margin-left和margin-top之值,使得这两个属性值随着宽和高的值动态变化而变化。
2、就是网友杨正祎(阿一)所提供的方法,也是不含有JavaScript的。

我觉得还是方法1较好些!
回复  3楼 回到顶楼 

你还不是小组成员,加入小组以后才能发布新主题!
> 返回“web标准设计”


其他话题

1 21060