<div class="parent">
<div class="child"></div>
</div>
flex
元素宽度已知
<style>
.parent {
width: 300px;
height: 300px;
border: 2px solid red;
display: flex;
justify-content: center;
align-items: center;
}
.child {
width: 100px;
height: 100px;
border: 2px solid green;
}
</style>
position(一)
元素宽度已知
<style>
.parent {
width: 300px;
height: 300px;
border: 2px solid red;
position: relative;
}
.child {
width: 100px;
height: 100px;
border: 2px solid green;
position: absolute;
left: 50%;
top: 50%;
margin: -50px 0 0 -50px;
}
</style>
position(二)
元素宽度已知
<style>
.parent {
width: 300px;
height: 300px;
border: 2px solid red;
position: relative;
}
.child {
border: 2px solid green;
width: 100px;
height: 100px;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
}
</style>
position transform
元素宽度未知
<style>
.parent {
width: 300px;
height: 300px;
border: 2px solid red;
position: relative;
}
.child {
width: 100px;
height: 100px;
border: 2px solid green;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
</style>
网友评论