html中的居中方法合集

1. `.one` 和 `.one-son`:
   - `.one` 使用 `text-align: center;` 属性将父元素中的文本内容水平居中对齐。
   - `.one-son` 使用 `display: inline-block;` 属性将子元素变为行内块元素,以便使其在一行内显示。
2. `.two` 和 `.two-son`:
   - `.two` 使用 `margin: auto;` 属性来使父元素水平和垂直居中。然而,这个方法仅对具有固定宽度和高度的块元素生效。
   - `.two-son` 使用 `margin: auto;` 属性使子元素在父元素中水平和垂直居中。然而,这种方法会影响其他元素的布局。
3. `.three` 和 `.three-son`:
   - `.three` 使用 `position: relative;` 属性将父元素设置为相对定位,为子元素的绝对定位提供参考。
   - `.three-son` 使用 `position: absolute;` 属性将子元素设置为绝对定位,并使用 `left: 50%;` 和 `margin-left: -50px;` 属性使子元素在父元素中水平居中。`left: 50%;` 将子元素的左边缘移动到父元素的水平中心,而 `margin-left: -50px;` 则通过负的子元素宽度的一半将其居中。
4. `.four` 和 `.four-son`:
   - `.four` 使用 `display: flex;` 属性将父元素设置为弹性盒子,以便对其子元素进行灵活的布局。
   - `.four` 使用 `justify-content: center;` 属性将子元素在主轴上居中对齐。
 


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        #dad{
            width: 200px;
            height: 200px;
            background-color: antiquewhite;
        }
        #son{
            width: 100px;
            height: 100px;
            background-color: blue;
        }
        /* 父级居中,子集变块 */
        .one{
            text-align: center;
        }
        .one-son{
            display: inline-block;
        }
        /* margin: auto;会影响其他元素 */
        .two{
            margin: auto;
        }
        .two-son{
            margin: auto;
        }
        /* position方法 */
        .three{
            position: relative;
        }
        .three-son{
            position: absolute;
            left: 50%;
            margin-left: -50px;
        }
        /* 弹性盒子 */
        .four{
            display: flex;
            justify-content: center;
        }
    </style>
</head>
<body>
    <!-- 第一种 -->
    <div id="dad" class="one">
        <div id="son" class="one-son" ></div>
    </div>
    <br>
    <!-- 第二种 -->
    <div id="dad" class="two">
        <div id="son" class="two-son"></div>
    </div>
    <br>
    <!-- 第三种 -->
    <div id="dad" class="three">
        <div id="son" class="three-son"></div>
    </div><br>
        <!-- 第四种 -->
    <div id="dad" class="four">
        <div id="son" class="four-son"></div>
    </div><br>
</body>
</html>

效果图:


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

校园小白

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值