为了账号安全,请及时绑定邮箱和手机立即绑定

请问为什么我的父元素和祖先元素都设置了相对定位,但子元素定位仍然依照祖先元素?

<!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">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>混合布局编程挑战</title>
<style type="text/css">
body{ 
margin:0;
padding:0;
font-size:30px;
color:#fff;
position: relative;
}
.top{
position: absolute;
top: 0px;
left: 0px;
background: blue;
}
.main{
background: red;
position: relative;
}
.left{
background: #abcdef;
width: 200px;
float: left;
position: absolute;
top: 0;
left: 0;
}
.right{
background: green;
margin:0 0 200px 0;
}
.foot{
background: #000;
clear: both;
}
</style>


</head>
<body>
<div class="top">top</div>
<div class="main">
    <div class="right">right</div>
    <div class="left">left</div>
</div>
<div class="foot">foot</div>
</body>
</html>


正在回答

1 回答

body不用设置relative,此时.top中的absolute仍然以body绝对定位,这个时候你是看不到top,因为绝对定位挺复杂这里不多说,后面main又设置了relative,这时,.left对父元素main绝对定位,建议以后浮动和定位不要一起用。


这个代码,你试试

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title></title>

<style type="text/css">

*{margin:0;padding:0;}

body{

font-size:30px;

color:#fff;

}

.top{

background: blue;

}

.main{

height: 300px;

background: red;

position: relative;

}

.left{

background: #abcdef;

width: 200px;

position: absolute;

top: 0;

left: 0;

}

.right{

background: green;

float:right;

}

.foot{

background: #000;

}

</style>

</head>

<body>

<div class="top">top</div>

<div class="main">

   <div class="right">right</div>

   <div class="left">left</div>

</div>

<div class="foot">foot</div>

</body>

</html>


0 回复 有任何疑惑可以回复我~
#1

Amaranta 提问者

非常感谢!
2017-02-25 回复 有任何疑惑可以回复我~

举报

0/150
提交
取消
如何用CSS进行网页布局
  • 参与学习       209677    人
  • 解答问题       1153    个

用最简洁的案例教你布局的那些知识,这是前端工程师基本技能

进入课程

请问为什么我的父元素和祖先元素都设置了相对定位,但子元素定位仍然依照祖先元素?

我要回答 关注问题
意见反馈 帮助中心 APP下载
官方微信