實現元素水平垂直居中的幾種方法:
<div id="wrap">
<div class="box"></div>
</div>
1. 定位方法實現水平垂直居中
<style>
*{
margin: 0;
padding: 0;
}
#wrap {
width: 500px;
height: 500px;
background: grey;
position: relative;
}
#wrap .box {
width: 200px;
height: 200px;
background: pink;
left: 0;
right: 0;
top: 0;
bottom: 0;
margin: auto;
position: absolute;
}
</style>
定位和transform方法實現元素水平垂直居中
<style>
*{
margin: 0;
padding: 0;
}
#wrap {
width: 500px;
height: 500px;
background: grey;
position: relative;
}
#wrap .box {
width: 200px;
height: 200px;
background: pink;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
</style>
3. 最新版本的flex實現元素的水平垂直居中
<style>
*{
margin: 0;
padding: 0;
}
#wrap {
width: 500px;
height: 500px;
background: grey;
display: flex;
justify-content: center;
align-items: center;
}
#wrap .box {
width: 200px;
height: 200px;
background: pink;
}
</style>
4. 使用老版本flex實現元素水平垂直居中
<style>
*{
margin: 0;
padding: 0;
}
#wrap {
width: 500px;
height: 500px;
background: grey;
display: -webkit-box;
-webkit-box-pack: center;
-webkit-box-align: center;
}
#wrap .box {
width: 200px;
height: 200px;
background: pink;
}
</style>
用純css創建一個三角形
主要是把高度和寬度設置成爲0,用邊框來實現三角形效果
html代碼:
<div id="box">
</div>
css代碼:
<style>
*{
margin: 0;
padding: 0;
}
#box {
width: 0px;
height: 0px;
border: 100px solid ;
border-top-color: red;
border-right-color: blue;
border-left-color: yellowgreen;
border-bottom-color: deeppink;
}
</style>
![image.png](https://imgconvert.csdnimg.cn/aHR0cHM6Ly9jZG4ubmxhcmsuY29tL3l1cXVlLzAvMjAyMC9wbmcvMTQ4MTQ2LzE1ODc1MTMxNDUyNTItYTIzMjk5ZDUtMzVjOC00ZmJkLTk3NmEtNDY3ODVhMzA4MDZmLnBuZw?x-oss-process=image/format,png#align=left&display=inline&height=247&margin=[object Object]&name=image.png&originHeight=494&originWidth=542&size=13252&status=done&style=none&width=271)
由上圖效果可以根據自己需要三角形類型改成相應邊框的顏色,不需要的邊框設置成transparent
如例子:左邊和上邊的邊框設置成紅色
#box {
width: 0px;
height: 0px;
border: 100px solid ;
border-top-color: red;
border-right-color: transparent;
border-left-color: red;
border-bottom-color:transparent ;
}
![image.png](https://imgconvert.csdnimg.cn/aHR0cHM6Ly9jZG4ubmxhcmsuY29tL3l1cXVlLzAvMjAyMC9wbmcvMTQ4MTQ2LzE1ODc1MTM0NDYwMzctZjE2Mzg4YWItMmJiNC00YjdkLTliN2UtYWI1YzEyYTA0OTRkLnBuZw?x-oss-process=image/format,png#align=left&display=inline&height=219&margin=[object Object]&name=image.png&originHeight=438&originWidth=506&size=10239&status=done&style=none&width=253)
如何實現移動端rem適配
html根元素的字體大小設置屏幕區域的寬
<div id="box">
</div>
<style>
*{
margin: 0;
padding: 0;
}
#box {
width: 1rem;
height: 1rem;
background: red;
}
</style>
<script type="text/javascript">
window.onload = function () {
// 獲取屏幕區域寬度
var width=document.documentElement.clientWidth
// 獲取html
var htmlNode = document.querySelector('html')
// 設置字體大小
htmlNode.style.fontSize= width + 'px'
}
</script>