前端Html+CSS常见布局及写法

做前端有一段时间了,慢慢的也积累了不少经验,现在记录下自己的经验,水平居中的页面布局中最为常见的一种布局形式,多出现于标题,以及内容区域的组织形式,下面介绍四种实现水平居中的方法(注:下面各个实例中实现的是child元素的对齐操作,child元素的父容器是parent元素)

前端Html+CSS常见布局及写法

1. 水平居中 

  使用display:inline 和 text-align

/*.parent {
    text-align: center;
}
.child {
    display: inline-block;
}*/

使用margin:0 auto 设定 

.child {
    width: 300px;
    margin: 0 auto;
}

使用table实现

.child{display: table; margin: 0 auto;}

 使用绝对定位

.parent{position:relative;}
.child{position:absolute; left:50%; transform:translate(-50%);}

 使用flex布局

/*第一种方法*/
.parent{display:flex; justify-content:center;}
/*第二种方法*/
.parent{display:flex;}
.child{margin:0 auto;}

html代码:

<body>
    <div class=‘parent‘>
        <div id=‘child‘ class="child">
            <p> 测试。。 测试。。111</p>
        </div>
    </div>
</body>

2.垂直居中

vertical -align 

只有一个元素属于inline或是inline-block(table-cell也可以理解为inline-block水平)水平,其身上的vertical-align属性才会起作用。
使用vertical-align的时候,由于对齐的基线是用行高的基线作为标记需要设置line-height或设置display:table-cell.

/*1*/
.parent{display:table-cell;vertical-align:middle;height:20px;}
/*2*/
.parent{display:inline-block;vertical-align:middle;line-height:20px;}

 绝对定位

.parent{position:relative;}
.child{positon:absolute; top:50%; transform:translate(0,-50%);}

 flex实现

.parent{display:flex; align-items:center;}

3.水平垂直居中

vertical-align text-aling inline-block
.parent{display:table-cell; vertical-align:middle; text-align:center;}
.child{display:inline-block;}

绝对定位

.parent{position:relative;}
.child{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);}

flex实现

.parent{display:flex;justify-content:center;align-items:center;}

以上只是单列布局,仅供参考!

文章声明:以上内容(如有图片或视频亦包括在内)除非注明,否则均为网站名称原创文章,转载或复制请以超链接形式并注明出处。https://xz.itlaoli.com/blog/547.html

« 上一篇
下一篇 »

相关推荐

想搭Halo博客?MySQL和PostgreSQL怎么选?看完这篇就懂了

2025年09月02日

6836阅读

告别局域网限制,cpolar 内网穿透+宝塔面板,公网远程访问超简单

2025年08月26日

3795阅读

windows修改服务器远程桌面端口图文教程

2025年08月04日

3681阅读

为什么本地 HTML、JS、JSON 文件会出现跨域问题?

2025年07月18日

4255阅读

搭建自己的技术博客有什么意义?

2025年07月03日

4176阅读

解决Zblog文章中Emoji表情显示为问号的问题​

2025年06月30日

3910阅读

发表评论

访客 访客
评论列表 (有 4 条评论,9953人围观)
网友昵称:阳阳
阳阳 V 游客 WeChat 7.0.17 Apple iPhone 椅子
2020年11月04日 来自天津 回复
看见了
网友昵称:121
121 V 游客 Google Chrome 87.0.4280.141 Windows 10 x64
2021年01月19日 来自上海 回复
@阳阳 这个留言板样式 是自己写的么
网友昵称:李洋博客
李洋博客 V 博主 Sogou Explorer Windows 10 x64
2021年01月20日 来自上海 回复
@121 是的!
网友昵称:我爱LY
我爱LY V 游客 Google Chrome 86.0.4195.1 Windows 10 x64 沙发
2020年10月31日 来自天津 回复
学习布局!
取消
微信二维码
微信二维码
支付宝二维码