前往小程序,Get更优阅读体验!
立即前往
发布
社区首页 >专栏 >前端面试 【CSS】— 让元素水平居中的方法有哪些?

前端面试 【CSS】— 让元素水平居中的方法有哪些?

作者头像
越陌度阡
发布2021-11-11 14:35:04
发布2021-11-11 14:35:04
70600
代码可运行
举报
运行总次数:0
代码可运行

如何让元素水平居中?这是一道很常见的面试题,对于已知宽度和未知宽度的处理方法又有所不同,大致有以下7种:

代码语言:javascript
代码运行次数:0
复制
<!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>让元素水平居中的方法有哪些</title>
    <style>
        *{
            margin:0;
            padding:0;
        }
        body>div{
            height:100px;
        }
    </style>
</head>
<body>
       
    <div style="width:288px;margin:0 auto;">
        用固定宽度加外边距自动实现水平居中
    </div>
 
        
    <div style="position:relative;">
        <!-- margin-left为width宽度的一半 -->
        <div style="width:288px;position:absolute;left:50%;margin-left:-144px">
            用绝对定位加负的左外边距实现水平居中
        </div>
    </div>
 

    <div style="text-align:center;">
        <span>用文本居中让行内元素水平居中</span>
    </div>
 
    <div style="text-align:center;">
        <div style="display:inline-block;">
            用文本居中加行内块实现水平居中
        </div>
    </div>

    <div style="position:relative;">
        <!-- 如果还想要子元素垂直居中,可以加上:top:50%;transform 改成 translate(-50%,-50%); -->
        <div style="position:absolute;left:50%;transform:translateX(-50%);">
            用绝对定位加平移实现水平居中
        </div>
    </div>
 
    <div style="display:table;margin:0 auto">
        <!-- 想要垂直居中可以在子元素上加上:display:table-cell;vertical-align:middle -->
        <span>用表格布局加外边距自动实现水平居中</span>
    </div>

    <div style="display:flex;justify-content:center;">
        <span>用弹性布局加文本对齐居中实水平居中</span>
    </div>

</body>
</html>
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2021/11/10 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档