<div style="width:600px;heigth:600px"><!--这个是父元素-->
<div class="son"><!--这个是子元素-->
<h1 class="title">hello word</h1>
<div class="content">这里面是一堆元素</div>
</div>
</div>
知道父元素的宽度和height,直接通过css写的width和height, 子元素没有通过style设置width和height,而是通过子元素中内部的元素将其撑开来计算的。
如何让这个子元素居中?
测试过的失败的方法
margin-top:50%; margin-top:-50%; margin-top的百分数是根据父元素的width计算的。
父元素 position:relative; 子元素position:absolute;top:0;right:0;bottom:0;left:0 失败,子元素如果不设置width和height就会直接继承到父元素的width和height,而不是通过内容撑开的宽度和高度。
父元素position:relative;子元素position:absolute:top:50%; 子元素里面加一层div设置position:absolute;top:-50%;top百分比里是根据父元素设定,子元素absolute,父元素继承不到高度。
父元素position:relative;子元素position:absolute:top:50%; 子元素里面加一层div设置position:relative;top:-50%;
这个最接近正确的答案,但是还是是错误的,在chrome的盒子模型里面已经显示出了relative的偏移量,但是渲染的时候并没有被渲染出来,top-50%;无效果。
不考虑ie可以用盒式模型。考虑ie只能js计算了
<style>
.parent{
width:600px;
height:600px;
display:-webkit-box;
display:-moz-box;
-moz-box-align:center;
-webkit-box-align:center;
-moz-box-pack:center;
-webkit-box-pack:center;
background:#aaa;}
</style>
<div class="parent">
<!--这个是父元素-->
<div class="son">
<!--这个是子元素-->
<h1 class="title">hello word</h1>
<div class="content">这里面是一堆元素</div>
</div>
</div>