實現(xiàn)效果:

image.png
有固定寬高:
- 方法1:
設置盒子position為absolute,注意設置父元素position為relative,然后給盒子設置top和left為父盒子的50%,最后使用margin-left和margin-top等于高寬的一半。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
.box{
width:400px;
height: 200px;
background-color: #ccc;
position: absolute;
top:50%;
left: 50%;
margin-left: -200px;
margin-top: -100px;
overflow:hidden;
}
.cir1,.cir2{
position: absolute;
width: 100px;
height: 100px;
border-radius: 50%;
background-color: #fc0;
}
.cir1{
top:-50px;
left:-50px;
}
.cir2{
bottom: -50px;
right: -50px;
}
</style>
</head>
<body>
<div class="box">
<div class="cir1"></div>
<div class="cir2"></div>
</div>
</body>
</html>
- 方法2:
依然是利用position,給子元素absolute定位,并且定位的上下左右都設置為0,margin為auto,父元素relative定位。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" href="4-1.css">
<style>
.box{
width:400px;
height: 200px;
background-color: #ccc;
position: absolute;
top:0;
left: 0;
bottom: 0;
right: 0;
margin: auto;
overflow:hidden;
}
.cir1,.cir2{
position: absolute;
width: 100px;
height: 100px;
border-radius: 50%;
background-color: #fc0;
}
.cir1{
top:-50px;
left:-50px;
}
.cir2{
bottom: -50px;
right: -50px;
}
</style>
</head>
<body>
<div class="wrap">
<div class="box">
<div class="cir1"></div>
<div class="cir2"></div>
</div>
</div>
</body>
</html>
高寬不固定:
- 方法1:還是用定位,但是不用margin-left和margin-top退回半個寬高,而是用css3的transform屬性退回50%;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" href="4-1.css">
<style>
.box{
/*width:400px;
height: 200px;*/
background-color: #ccc;
position: absolute;
top:50%;
left:50%;
overflow:hidden;
transform:translate(-50%,-50%);
}
.cir1,.cir2{
position: absolute;
width: 100px;
height: 100px;
border-radius: 50%;
background-color: #fc0;
}
.cir1{
top:-50px;
left:-50px;
}
.cir2{
bottom: -50px;
right: -50px;
}
</style>
</head>
<body>
<div class="wrap">
<div class="box">
balabalaliliaa
如果使用import方法對CSS進行導入,會導致某些頁面在Windows 下的Internet Explorer出現(xiàn)一些奇怪的現(xiàn)象:以無樣式顯示頁面內(nèi)容的瞬間閃爍,這種現(xiàn)象稱之為文檔樣式短暫失效(Flash of Unstyled Content),簡稱為FOUC。
why?
使用import導入樣式表
將樣式表放在頁面底部
有幾個樣式表,放在頁面不同位置
原因即:當樣式表晚于結(jié)構性html加載,當加載到此樣式表時,頁面將停止之前的渲染。此樣式表被下載和解析后,將重新渲染頁面,也就出現(xiàn)了短暫的花屏現(xiàn)象。
how?
<div class="cir1"></div>
<div class="cir2"></div>
</div>
</div>
</body>
</html>

image.png
- 方法2:
flex布局:
給父元素設置display:flex,justify-content:center,水平居中。align-items:center垂直居中,不知道為啥不行,?必須得在子元素設置 align-self:center才可以。
.div1{
width:500px;
height:500px;
border:1px solid black;
display: flex;
justify-content: center; /*使垂直居中*/
align-items:center; /*使水平居中*///不可以
}
.div2{
background: yellow;
/*width:300px;
height:200px;*/
align-self:center
}
- 方法3: