首页 话题 小组 问答 好文 用户 我的社区 域名交易 唠叨

[分享]css中怎么设置div居中

发布于 2024-11-11 18:47:42
0
12

CSS中如何让div居中显示呢?以下是几种方法:

1.使用margin属性

<style>
    div {
        width: 200px;
        height: 100px;
        background-color: red;
        margin: auto;
    }
</style>

<div></div> 

使用margin属性设置上下左右的值都为自动,即可让div在其父元素中水平和垂直居中显示。

2.使用flex布局

<style>
    .container {
        display: flex;
        justify-content: center; /*水平居中*/
        align-items: center; /*垂直居中*/
        height: 100vh;
    }

    .item {
        width: 200px;
        height: 100px;
        background-color: red;
    }
</style>

<div class="container">
    <div class="item"></div>
</div> 

使用flex布局,将父元素的display属性设置为flex,同时设置justify-content和align-items属性,即可实现div的水平和垂直居中。

3.使用absolute布局

<style>
    .container {
        position: relative;
        height: 100vh;
    }

    .item {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        width: 200px;
        height: 100px;
        background-color: red;
    }
</style>

<div class="container">
    <div class="item"></div>
</div> 

使用absolute布局,设置父元素的position属性为relative,设置div的position属性为absolute,同时设置top、left和transform属性,即可实现div的水平和垂直居中。

评论
一个月内的热帖推荐
91云脑
Lv.1普通用户

62849

帖子

14

小组

291

积分

赞助商广告
站长交流