一、子级绝对定位+transform
<style>
.out {
position: relative;
width: 500px;
height: 500px;
background-color: blue;
}
.in {
position: absolute;
left: 50%;
top: 50%;
/* transform: translateX(-50%) translateY(-50%); */
transform: translate(-50%,-50%);
background-color: pink;
}
</style>
<body>
<div class="out">
<div class="in">111111111111</div>
</div>
</body>
二、 父级flex弹性布局
<style>
.out {
width: 400px;
height: 400px;
background-color: pink;
display: flex;
align-items: center;
justify-content: center;
}
.in {
background-color: blueviolet;
}
</style>
<body>
<div class="out">
<div class="in">11111111111</div>
</div>
</body>
三、父级添加table属性,子级添加table-cell
<style>
.out {
display: table;
width: 500px;
height: 500px;
background-color: pink;
}
.in {
/* 这种方式只能让文字或是图片水平垂直居中 */
display: table-cell;
vertical-align: middle;
text-align: center;
/* 背景色会占掉整个父元素的位置 */
/* background-color: blue; */
}
/*我的图片太大了所以设了宽高限制一下*/
img {
width: 100px;
height: 100px;
}
</style>
<body>
<div class="out">
<!-- <div class="in">11111111111111</div> -->
<div class="in"><img src="../img/日落.jpg" alt=""></div>
</div>
</body>