div盒子里面的内容居中
时间: 2023-11-07 17:15:14 浏览: 101
要让div
盒子里面的内容居中,可以使用以下三种方法:
方法一:利用相等的顶部内边距和底部内边距填充将子分区置于父分区的中心。可以设置父容器的上下内边距为相等的值,并将子容器的margin
属性设置为0 auto
。示例代码如下:
<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%);
将子容器居中。示例代码如下:
<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
即可将子容器居中。示例代码如下:
<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
盒子里面内容的居中显示。123
引用[.reference_title]
- 1 2 3 常用的8种实现div盒子居中的方法[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
allinsert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]
相关推荐
















