html如何上下垂直居中

HTML上下垂直居中的实现方法有以下几种:

html如何上下垂直居中
(图片来源网络,侵删)

1、使用flex布局

2、使用grid布局

3、使用定位和transform属性

4、使用tablecell和verticalalign属性

5、使用lineheight属性

下面分别介绍这几种方法:

1. 使用flex布局

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF8">
    <meta name="viewport" content="width=devicewidth, initialscale=1.0">
    <title>Flex布局上下垂直居中</title>
    <style>
        .container {
            display: flex;
            alignitems: center;
            justifycontent: center;
            height: 100vh; /* 设置容器高度为视口高度 */
        }
    </style>
</head>
<body>
    <div class="container">
        我是垂直居中的内容
    </div>
</body>
</html>

2. 使用grid布局

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF8">
    <meta name="viewport" content="width=devicewidth, initialscale=1.0">
    <title>Grid布局上下垂直居中</title>
    <style>
        .container {
            display: grid;
            justifyitems: center;
            alignitems: center;
            height: 100vh; /* 设置容器高度为视口高度 */
        }
    </style>
</head>
<body>
    <div class="container">
        我是垂直居中的内容
    </div>
</body>
</html>

3. 使用定位和transform属性

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF8">
    <meta name="viewport" content="width=devicewidth, initialscale=1.0">
    <title>定位和transform属性上下垂直居中</title>
    <style>
        .container {
            position: relative; /* 设置容器为相对定位 */
            height: 100vh; /* 设置容器高度为视口高度 */
        }
        .center {
            position: absolute; /* 设置内容为绝对定位 */
            top: 50%; /* 距离顶部50% */
            left: 50%; /* 距离左侧50% */
            transform: translate(50%, 50%); /* 向左上移动自身宽高的一半,实现垂直居中 */
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="center">我是垂直居中的内容</div>
    </div>
</body>
</html>

4. 使用tablecell和verticalalign属性

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF8">
    <meta name="viewport" content="width=devicewidth, initialscale=1.0">
    <title>tablecell和verticalalign属性上下垂直居中</title>
    <style>
        .container {
            height: 100vh; /* 设置容器高度为视口高度 */
            display: table; /* 将容器设置为表格 */
        }
        .center {
            display: tablecell; /* 将内容设置为表格单元格 */
            verticalalign: middle; /* 垂直对齐方式为居中 */
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="center">我是垂直居中的内容</div>
    </div>
</body>
</html>

原创文章,作者:未希,如若转载,请注明出处:https://www.kdun.com/ask/428396.html

(0)
未希的头像未希新媒体运营
上一篇 2024-04-03 23:09
下一篇 2024-04-03 23:10

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

免费注册
电话联系

400-880-8834

产品咨询
产品咨询
分享本页
返回顶部
云产品限时秒杀。精选云产品高防服务器,20M大带宽限量抢购  >>点击进入