关于盒子模型之 水平居中和垂直居中的问题

一,水平居中

水平居中可分为行内元素水平居中和块级元素水平居中

1.行内元素水平居中

定义:行内元素是指文本text、图像img、超链接等,只需给父元素设置text-align:center即可实现。

.box {
        text-align:center;
}
<div class="box">水平居中</div>

2,块元素水平居中

2.1 给块元素设置宽 ,只需给需要居中的块级元素加margin:0 auto即可。

.box{
        width:200px;
        margin:0 auto;
}
<div class="box">网蒂娜</div>

2.2 不给块元素设置宽

方法一:给所需元素居中的元素设置 display:table,然后设置margin:0 auto来实现

    <style>
        .box {
            display: table;
            margin: 0 auto;
            border: 1px solid red;
        }
    </style>
</head>

<body>

    <div class="box">帮后分视。</div>
</body>

方法二:通过给子元素设置inline-block,然后再给父元素设置text-align:center

    <style>
        .box1 {
            text-align: center;
        }

        .box1{
            display: inline-block;
        }
    </style>
</head>

<body>

    <div class="box">
        <div class="box1">1</div>
        <div class="box1">2</div>
    </div>
</body>

方法三:给有需要的的块状元素的父元素设置display:flex,justify-content:center;

    <style>
        .box {
            display: flex;
            justify-content: center;
        }
    </style>
</head>

<body>

    <div class="box">
        <div class="box1">量千韩。</div>
        <div class="box1">量千韩。</div>
    </div>
</body>

二,垂直居中

方法一:固定高宽div垂直居中(使用绝对定位和负外边距)

 position: absolute;
 left: 50%;
 top: 50%;
width:200px;
height:100px;
margin-left:-100px;
margin-top:-50px;

方法二:伪元素和inline-block、vertical-align

    <style>
        .box {
            height: 300px;
            text-align: center;
            background-color: blue;
        }

        .box:before {
            content: '';
            display: inline-block;
            height: 100%;
            vertical-align: middle;
            margin-right: -0.25em;
        }

        .box1 {
            display: inline-block;
            vertical-align: middle;
            width: 50%;
            background-color: aqua;
        }
    </style>
</head>

<body>
    <div class="box">
        <div class="box1">
            <h1>远你憾。</h1>
            <p>守磊拢。</p>
        </div>
    </div>
</body>

方法三:table-cell实现水平垂直居中: table-cell middle center组合使用

    <style>
        .table-cell {
            display: table-cell;
            vertical-align: middle;
            text-align: center;
            width: 240px;
            height: 180px;
            border: 1px solid #666;
        }
    </style>
</head>

<body>
    <div class="table-cell">
        <p>我爱你中国</p>
    </div>
</body>

此文章仅供参考。

  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值