div盒子里面的内容居中
时间: 2023-11-07 12:15:14 浏览: 91
要让`div`盒子里面的内容居中,可以使用以下三种方法:
方法一:利用相等的顶部内边距和底部内边距填充将子分区置于父分区的中心。可以设置父容器的上下内边距为相等的值,并将子容器的`margin`属性设置为`0 auto`。示例代码如下:
```html
<style>
.bigbox {
width: 500px;
background-color: pink;
margin: 0 auto;
padding: 9% 0;
}
.box {
width: 100px;
height: 100px;
background-color: aqua;
text-align: center;
line-height: 100px;
margin: 0 auto;
}
</style>
</head>
<body>
<div class="bigbox">
<div class="box"></div>
</div>
</body>
```
方法二:使用绝对定位,设置父容器的`position`属性为`relative`,设置子容器的`position`属性为`absolute`,并通过设置`top: 50%; left: 50%; transform: translate(-50%, -50%);`将子容器居中。示例代码如下:
```html
<style>
.bigbox {
width: 500px;
height: 500px;
background-color: pink;
margin: 0 auto;
position: relative;
}
.box {
width: 100px;
height: 100px;
background-color: aqua;
text-align: center;
line-height: 100px;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
</style>
</head>
<body>
<div class="bigbox">
<div class="box">居中</div>
</div>
</body>
```
方法三:利用弹性盒子和`justify-content: center;align-items: center`结合使用。将父容器设置为弹性容器,并设置`justify-content: center;align-items: center`即可将子容器居中。示例代码如下:
```html
<style>
.bigbox {
width: 500px;
height: 500px;
background-color: pink;
margin: 0 auto;
display: flex;
justify-content: center;
align-items: center;
}
.box {
width: 100px;
height: 100px;
background-color: aqua;
text-align: center;
line-height: 100px;
}
</style>
</head>
<body>
<div class="bigbox">
<div class="box">居中</div>
</div>
</body>
```
以上是三种常用的方法,可以根据具体需求选择适合的方式来实现`div`盒子里面内容的居中显示。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* *2* *3* [常用的8种实现div盒子居中的方法](https://blog.csdn.net/qq_52409560/article/details/127042537)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 100%"]
[ .reference_list ]
阅读全文