<!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>元素居中的两种方法</title>
<style>
.box {
width: 15em;
height: 15em;
background-color: crimson;
position: relative;
}
.box .sun {
width: 5em;
height: 5em;
background-color: darkblue;
position: absolute; /**绝对定位*/
top: 0;
left: 0;
right: 0;
bottom: 0; /**top left right bottom 等于0让盒子居中*/
margin: auto; /*这一行才做了sun 元素再box中的居中效果,没有的话无效果*/
}
.box1 {
width: 15em;
height: 15em;
background-color: darkorange;
display: flex;
justify-content: center;
align-items: center;
/** display: flex;justify-content: center; align-items: center; 完成了利用flex居中效果*/
}
.box1 .sun1 {
width: 5em;
height: 5em;
background-color: darkslateblue;
}
</style>
</head>
<body>
<h2>传统居中</h2>
<div class="box">
<div class="sun"></div>
</div>
<h2>flex居中</h2>
<div class="box1">
<div class="sun1"></div>
</div>
</body>
</html>
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!