DIV+CSS练习2

来源:互联网 发布:双色球系统分析软件 编辑:程序博客网 时间:2024/05/16 11:20
 用5个DIV实现水平垂直均居中显示一个宽50px,高200px的正十字架,用两种方法实现 
大概试了下,然后也百度了一下,发现是某年腾讯的面试题,原题是显示宽50px,高150px的十字架,分别用2个,3个,5个DIV构造。
今天练习了5个的,慢慢的调试关于margin负值有了点新的理解
了解的一点小知识:当static元素的margin-top/margin-left被赋予负值时,元素将被拉进指定的方向。
eg:div1{margin-top:-10px}          div1就会相对于它原来的位置上移10px。

但如果你设置margin-bottom/right为负数,元素并不会如你所想的那样向下/右移动,而是将后续的元素拖拉进来,覆盖本来的元素。

如果没有设定width属性,设定负margin-left/right会将元素拖向对应的方向,并增加宽度,此时的margin的作用就像padding一样。


自己大概琢磨了两种方法
1.margin负值

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta charset="utf-8"3>
<title>十字架</title>
<style type="text/css">
<!--
#top,#bottom{
position: absolute;
height: 76px;
width: 50px;
left:50%;
top:50%;
}
#left,#right,#center{
position: absolute;
height: 50px;
width: 50px;
left:50%;
top:50%;
}
#center{
margin: -25px 0px 0px -25px;
background:#de534e;
}
#top{
margin: -101px 0px 0px -25px;/*实验了很多次调到合适,本来认为是88px发现不行,但是不知道为什么是101*/
background:#fd6d6d;
}
#left{
margin:-25px 0px 0px -75px;
background:#fd6d6d;
}
#bottom{
margin:25px 0px 0px -25px;
background-color: #fd6d6d;
}

#right{
margin:-25px 0px 0px 25px;
background:#fd6d6d;
}
}
-->
</style>
</head>
<body>
<div id="top"></div>
<div id="bottom"></div>
<div id="left"></div>
<div id="right"></div>
<div id="center"></div>
</body>
</html>

2.position

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta charset="utf-8"3>
<title>十字架</title>
<style type="text/css">
<!--
#lt,#rt,#lb,#rb{
background-color: #ffffff;
height: 75px;
width: 50px;
position: absolute;
}
#center{
position:absolute;
margin: auto;
width:150px;
height:200px;
top: 0;bottom: 0;left: 0;right: 0;
background-color:#e84c3d;
}
#lt{
top:0px;
left: 0px;
}
#rt{
top: 0px;
right: 0px;
}
#lb{
bottom: 0px;
left: 0px;
}
#rb{
bottom: 0px;
right: 0px;
}
-->
</style>
</head>
<body>
<div id="center">
<div id="lt"></div>
<div id="rt"></div>
<div id="lb"></div>
<div id="rb"></div>
</div>
</body>
</html>


思考:想一下,用的是绝对定位还是相对定位?绝对定位的话,其定位祖先元素是什么?绝对定位与相对定位能否互换?效果会做出怎样改变??
 答:用的是绝对定位,center的祖先元素是body,剩下四个祖先元素是center,不能互换。
 如果要你再那四个白块用relative的话,主要用什么定位margin还是top那些比较好
试了下top的方法

#lt,#rt,#lb,#rb{
background-color: #000000;
height: 75px;
width: 50px;
position: relative;
}

#lt{
top:0px;
left: 0px;
}
#rt{
top: -75px;
right: -100px;
}
#lb{
top: -25px;
left: 0px;
}
#rb{
top: -100px;
right: -100px;
}


0 0