以下是题目的布局代码:
html
<div class="container">
<div class="item" style="width: 100px; height: 100px; background: #999;">
块状元素
</div>
</div>
<div class="container">
<div class="item">不定高宽的块状元素</div>
</div>
<div class="container">
<span class="item">行内元素</span>
</div>
css
.container {
// 把代码写在这里
}
.container {
height: 20rem;
background: #ccc;
margin: 1rem;
}
1.flex方法:
css
.container {
display: flex;
justify-content: center;
align-items: center;
}
2.grid方法:
css
.container {
display: grid;
place-items: center;
}
或
css
.container {
display: flex;
justify-content: center;
align-items: center;
}
3.绝对定位方法:
css
.container {
position: relative;
}
.item {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
.item {
padding: 1rem;
border: 1px solid #999;
}
.container {
height: 12rem;
background: #ccc;
margin: 1rem;
}