html居中代码怎么写?

<div>居中 - 法1

通过中心点,计算坐标来垂直居中。

<html>

<head>
    <style type="text/css">
        .content {
            background-color: rgb(87, 87, 92);
            position: absolute;
            /* 水平居中 */
            left: 50%;
            width: 30%;
            margin-left: -15%;
            /* 垂直居中 */
            top: 50%;
            height: 30%;
            margin-top: -15%;
        }
    </style>
</head>

<body>
    <div class="content">Content goes here</div>
</body>

</html>

<div>居中 - 法2
<html>

<head>
    <style type="text/css">
        #content {
            position: absolute;
            /* 垂直居中 */
            top: 0;
            bottom: 0;
            height: 50%;
            /* 水平居中 */
            left: 0;
            right: 0;
            width: 70%;
            margin: auto;
            background-color: red;
        }
    </style>
</head>

<body>
    <div id="content"> Content here</div>
</body>

</html>

垂直居中:vertical-align

设置单行或表格单元格内元素,垂直方向上的位置,不能用块级元素。可用属性值:top middle bottom 等,详细说明.

<html>

<head>
    <style type="text/css">
        .middle {
            vertical-align: middle;
        }
    </style>
</head>

<body>
    <div>
        An
        <img class="middle" src="https://mdn.mozillademos.org/files/12245/frame_image.svg" alt="link" width="32"
            height="32" />
        image with a middle alignment.
    </div>
</body>

</html>

文字居中:line-height

将文字line-height等于父容器的高度,即可垂直方向上居中;text-align可让文在水平方向上居中。

<html>
<head>
    <style type="text/css">
        #wrapper {
            height: 100px;
            background-color: red;
        }

        .content {
            /* 文字垂直居中 */
            line-height: 100px;
            /* 文字水平居中 */
            text-align: center;
        }
    </style>
</head>

<body>
    <div id="wrapper">
        <p class="content">Content goes here</p>
    </div>
</body>

</html>

参考链接
  • 12
    点赞
  • 64
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值