要想在网页上展示的内容合理、布局好看,那就少不了CSS定位与布局的应用。CSS网页定位分为三种:文档流定位、浮动定位和层定位,接下来分别讲一下这三种定位方式。
html中的元素按照是否独占一行可以分为:行内元素、块级元素和行内块元素。
display: none; 表示元素不会被显示
display: inline; 表示元素是行内元素
display: block; 表示元素是块级元素
display: inline-block; 表示元素是行内块元素
将元素设置成浮动定位后,元素将脱离文档流位置。浮动定位主要是float属性和clear属性。
float属性有三个值
float: none; 表示不浮动
float: left; 表示左浮动
float: right; 表示右浮动
接下来重点看一下左浮动和右浮动
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>floattitle>
<style>
#container {
margin: 0 auto;
width: 150px;
height: 150px;
background-color: #cccccc;
}
#box1 {
width: 50px;
height: 50px;
background-color: #138eee;
}
#box2 {
width: 50px;
height: 50px;
background-color: #66ccff;
}
style>
head>
<body>
<div id="container">
<div id="box1">box1div>
<div id="box2">box2div>
div>
body>
html>
将box1和box2都设置为left定位
#container {
margin: 0 auto;
width: 150px;
height: 150px;
background-color: #cccccc;
}
#box1 {
width: 50px;
height: 50px;
float: left;
background-color: #138eee;
}
#box2 {
width: 50px;
height: 50px;
float: left;
background-color: #66ccff;
}
将box1设置成left布局,box2设置成right布局
#container {
margin: 0 auto;
width: 150px;
height: 150px;
background-color: #cccccc;
}
#box1 {
width: 50px;
height: 50px;
float: left;
background-color: #138eee;
}
#box2 {
width: 50px;
height: 50px;
float: right;
background-color: #66ccff;
}
首先看一下,若将上述例子中的box1设置float:left定位,box2仍然是文档流定位,看一下有何效果。
#box1 {
width: 50px;
height: 50px;
float: left;
background-color: #138eee;
}
#box2 {
width: 50px;
height: 50px;
background-color: #66ccff;
}
从效果看,box2和box1颜色重叠了,只是box2的字在下面。那怎么让box1和box2正常显示呢?可以使用clear属性,将box2的clear设置成both,或者left都可以。
#box1 {
width: 50px;
height: 50px;
float: left;
background-color: #138eee;
}
#box2 {
width: 50px;
height: 50px;
/*clear: left;*/
clear: both;
background-color: #66ccff;
}
clear属性有四个取值:
例如:要想实现下面这种布局样式,可以通过设置position属性实现。
这种样式属于两行三列,其中第二行整个box可以设置成绝对定位,然后里面都可以设置成绝对定位。
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>position属性title>
<style>
* {
margin: 0;
padding: 0;
}
#header {
width: 100%;
height: 50px;
background-color: #66ccff;
}
#main_area {
position: absolute;
top: 50px;
left: 0;
right: 0;
bottom: 0;
background-color: pink;
}
#menu_side {
width: 100px;
height: 100%;
position: absolute;
top: 0;
left: 0;
bottom: 0;
background-color: #138eee;
}
#right_side {
position: absolute;
top: 0;
right: 0;
bottom: 0;
width: 150px;
background-color: #ccffff;
}
#content {
position: absolute;
top: 0;
bottom: 0;
left: 100px;
right: 150px;
background-color: #ffc600;
}
style>
head>
<body>
<div id="container">
<div id="header">头部div>
<div id="main_area">
<div id="menu_side">菜单栏div>
<div id="content">内容展示区div>
<div id="right_side">右侧栏div>
div>
div>
body>
html>
参考资料:中国大学慕课网上的《Web前端开发》(作者:孙俏 、王新阳 、祖明 、付慧)课程