定位:手动控制元素在包含块中的精准位置
涉及CSS属性:position
-默认值:static,静态定位(不定位)
-relative:相对定位
-absolute:绝对定位
-fixed:固定定位
一个元素,只要position的取值不是static,认为该元素是一个定位元素
定位元素会脱离文档流(相对定位除外)
一个脱离了文档流的元素:
不会导致元素脱离文档流,只是会让元素在原来的位置上进行偏移
可以通过四个CSS属性设置其位置:
其他情况和绝对定位完全一样
包含块不一样:固定为视口(浏览器的可视窗口)
某个方向居中:
堆叠上下文
设置z-index,通常情况下,该值越大,越靠近用户;只要定位元素设置z-index有效,z-index可以是负数,如果是负数,则遇到常规流、浮动元素,则会被其覆盖
1、二级菜单.html
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Documenttitle>
<link rel="stylesheet" href="css/reset.css">
<link rel="stylesheet" href="css/menu.css">
head>
<body>
<header class="header">
<ul class="topnav clearfix">
<li><a href="">Lororibe.a>li>
<li><a href="">Quibusdama>li>
<li><a href="">Nullaunta>li>
<li><a href="">客户服务a>
<div class="submenu">
<ul>
<li>hhhli>
<li>kkkli>
<li>nnli>
<li>iioli>
<li>iaishli>
ul>
div>
li>
<li><a href="">Quama>li>
ul>
header>
body>
html>
2、reset.css
/*通用的 */
h1{
font-size:1em;
font-weight:normal;
}
ol,
ul{
list-style:none;
}
blockquote,
q{
quotes:none;
}
blockquote:before,
blockquote:after,
q::before,
q::after{
content:'';
content:none;
}
table{
border-collapse: collapse;
border-spacing: 0;
}
a{
text-decoration:none ;
color:inherit;
}
3、menu.css
.clearfix::after{
content:"";
display: block;
clear:both;
}
.header{
color:#999;
background:#e3e4e5;
height:40px;
line-height: 40px;
/* position:fixed;
width:100%;
left:0;
top:0;*/
}
/* 表示只是选中子元素 */
.header .topnav>li{
float:left;
/* 注意高度坍塌 */
margin:0 20px;
width:150px;
text-align: center;
/* background-color: lightblue; */
height:40px;
box-sizing:border-box;
position: relative;
}
.header .topnav>li:hover{
background: #fff;
border:2px solid #ccc;
border-bottom: none;
line-height: 36px;
}
.header .topnav>li .submenu{
text-align: left;
line-height:1.5;
width:300px;
/* 不生成盒子 */
display: none;
border:2px solid #ccc;
box-sizing:border-box;
position:absolute;
right:-2px;
background-color: #fff;
}
.header .topnav>li:hover .submenu{
display:block;
}
.header .topnav>li:hover::after{
content:"";
position:absolute;
width:100%;
height:5px;
bottom:0;
left:0;
background: #fff;
}
4、最终效果