盒模型、定位与浮动
程序员文章站
2022-04-25 11:39:09
...
盒模型
所谓盒模型其实任意标签都有,可以让标签向外拓展。【padding、border、margin】
盒模型中padding【内边距】、border【外边框】可以让元素向外拓展。margin【外边距】和其他标签的距离。
盒模型:(margin + padding + border + width + heigh)
<style type="text/css">
div{
width: 200px;
height: 200px;
border: 20px solid red; /* 外边框 20,实线,红色*/
padding: 50px;
margin: 10px;
background-color: cyan;
}
.box1{
margin-top: 60px;/*标签与标签之间的距离*/
}
</style>
定位
可以打破文档流让标签可以在任意地方显示。
口诀:子绝父相
position属性
position: fixed; 固定定位
position: relative; // 相对定位
position: absolute; // 绝对定位
固定定位
- 给某一个标签固定在网页中某一个位置,哪怕页面上下滑动效果也不影响(不会动,也在页面固定位置)。
- 固定定位的位置只于当前网页的边框(的上、下、左、右)相关。比如一些网页左右的小广告。
- 固定定位元素不占用起始位置
<style type="text/css">
div{
width: 420px;
height: 240px;
}
#box{
position: fixed; //固定定位
left: 500px;
top: 200px;
background: red;
}
#box1{
background: green;
}
#box2{
background: purple;
}
.uuu{height: 4000px;}
</style>
</head>
<body>
<div id="box">1</div>
<div id="box1">2</div>
<div id="box2">3</div>
<div class="uuu"></div>
</body>
相对定位
- 相对的是标签的起始位置的偏离。页面上下滚动也会动
- 相对定位元素会占用起始位置。接下来的元素会把位置空下来。
<style type="text/css">
*{margin: 0;padding: 0;}
div{
width: 400px;
height: 200px;
}
.box{
background-color: red;
}
.box1{
position: relative; // 相对定位
background-color: green;
left: 500px;
top: 200px;
}
.box2{background-color: yellow;}
</style>
</head>
<body>
<div class="box">1</div>
<div class="box1">2</div>
<div class="box2">3</div>
</body>
绝对定位
- 绝对定位元素,如果没有定位父元素,参照页面进行偏移
- 绝对定位元素,如果有定位父元素,参照定位父元素进行偏移
- 绝对定位元素不占起始位置。回随页面滚动移动。
<style type="text/css">
div{
width: 400px;
height: 200px;
}
.box{
background-color: red;
}
.box1{
position: absolute; // 绝对定位
left: 100px;
top: 100px;
background-color: green;
}
.box2{
background-color: yellow;
}
.innter{
position: absolute;/*如果父有定位则参照父,如果父无定位则参照网页*/
width: 100px;
height: 100px;
left:50px;
top: 50px;
background-color: cyan;
}
</style>
</head>
<body>
<div class="box">1</div>
<div class="box1">
<div class="innter">
</div>
</div>
<div class="box2">
</div>
</body>
浮动
浮动就是让元素进行‘靠左、靠右’进行水平排列。(一行放不下会自动换行)
float: left;/*浮动:靠左侧*/
代码
<style type="text/css">
*{margin: 0;padding: 0;}
#box{
float: left;/*浮动:靠左侧*/
width: 200px;
height: 40px;
background-color: red;
}
</style>
</head>
<body>
<div id="box">气温</div>
<div id="box">气温</div>
<div id="box">气温</div>
<div id="box">气温</div>
<div id="box">气温</div>
<div id="box">气温</div>
</body>
拓展:使用css浮动与定位,做导航栏、轮播图