div、img的居中
2019-11-12 本文已影响0人
索哥来了
下面分为三块,知道div高度,不知道div高度,以及img的居中:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
*{
margin: 0;
padding: 0;
}
.div1{
border:1px solid #ccc;
width: 50px;
height: 50px;
padding: 10px;
position: relative;
margin: 20px;
}
/*知高*/
.div2{
width: 20px;
height: 20px;
position: absolute;
left: 50%;
top: 50%;
margin-left: -10px;
margin-top: -10px;
background: #ccc;
}
/*不知高*/
.div3{
line-height: 12px;
background: #ccc;
word-break: break-all;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
/*图片居中*/
.div1 img{
max-width: 50px;
max-height: 50px;
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
margin: auto;
}
</style>
</head>
<body>
<!-- 块在块居中 -->
<div class="div1">
<div class="div2"></div>
</div>
<div class="div1">
<div class="div3">aaaaaaaaa</div>
</div>
<!-- 图片在块居中 -->
<div class="div1">
<img src="1.jpg" alt="">
</div>
</body>
</html>