html+css 元素定位

body有默认的margin:8px
元素定位时用:position:和 left top配合使用,来确定元素的位置

1.absolute 绝对定位

feature:a.脱离原来的层进行定位(当一个元素成absolute元素时,会脱离原来的层)
b.相对于最近的有定位的父级进行定位,如果没有,相对于文档定位

没有定位时:
这里写图片描述
结果:
这里写图片描述

absolute定位之后:
这里写图片描述
这里写图片描述

2.relative 相对定位

feature:a.保留原来的层进行定位
b.相对于自己原来的位置进行定位
relative定位之后:
这里写图片描述
这里写图片描述

注:
relative 一般作为参照物来使用(父级)减少对子元素的破坏,absolute作为定位元素。

3.fixed 固定定位(广告定位)

html

<!DOCTYPE html>
<html>
<head>
    <title></title>
<link rel="stylesheet" href="1.css">
<style type="text/css">

</style>
</head>

<body>
    <div class="box">
        <div  class="content">
            <div>this is a AD</div>
        </div>
    </div>
</body>
</html>

css

*{
    margin:0;
    padding: 0;
}
.box{
    width: 200px;
    height: 100px;
    background-color: #ccc;
    border:1px solid black;
    position: fixed;
    left: 50%;
    top: 50%;
/*  因为left和top是相对于左顶点进行定位的,所以元素会偏右;
    将元素根据高宽的一半进行左上移动*/
    margin-left: -100px;
    margin-top: -50px;
}
.content{
    text-align: center;
    line-height: 100px;
}

这里写图片描述

小测试:做一个五环水平居中再屏幕
html

<!DOCTYPE html>
<html>
<head>
    <title></title>
<link rel="stylesheet" href="1.css">
<style type="text/css">

</style>
</head>

<body>
    <div class="plat">

            <div class="paint blue"></div>
            <div class="paint black"></div>
            <div class="paint red"></div>
            <div class="paint yellow"></div>
            <div class="paint green"></div> 
    </div>
</body
</html>

css

*{
    margin:0;
    padding: 0;
}
.plat{
    width: 320px;
    height: 160px;
    position: fixed;
    left: 50%;
    top: 50%;
/*  因为left和top是相对于左顶点进行定位的,所以元素会偏右;
    将元素根据高宽的一半进行左上移动*/
    margin-left: -160px;
    margin-top: -80px;
}
.paint{
    width: 100px;
    height:100px;
    border-radius: 50%;
    position: absolute;

}
.blue{
    border:3px solid blue;
    top: 0px;
    left: 0px;
}

.black{
    border:3px solid black;
    top: 0px;
    left: 110px;
    z-index: 3;
}
.red{
    border:3px solid red;
    top: 0px;
    left: 220px;
}
.yellow{
    border:3px solid yellow;
    top: 60px;
    left: 55px;
}
.green{
    border:3px solid green;
    top: 60px;
    left: 165px;
}

这里写图片描述

猜你喜欢

转载自blog.csdn.net/qq_39396275/article/details/81164490