在 linkedin 上关注我
在 github.com 上关注我
点击阅读
没有boaring setion,我们可以重定向到编码!
1.使用flexbox
flexbox 是一个强大的布局工具,可以轻松地将元素水平和垂直居中。
例子:
center div with flexbox .container { display: flex; justify-content: center; /* horizontal center */ align-items: center; /* vertical center */ height: 100vh; /* full viewport height */ } .centered-div { width: 200px; height: 200px; background-color: lightblue; }centered with flexbox
登录后复制
2.使用网格
css grid 是另一个强大的布局系统,可以轻松地将元素居中。
立即学习“前端免费学习笔记(深入)”;
例子:
center div with grid .container { display: grid; place-items: center; /* center both horizontally and vertically */ height: 100vh; /* full viewport height */ } .centered-div { width: 200px; height: 200px; background-color: lightcoral; }centered with grid
登录后复制
3. 使用绝对定位和变换
此方法涉及绝对定位 div 并使用变换使其居中。
例子:
center div with absolute positioning .container { position: relative; height: 100vh; /* full viewport height */ } .centered-div { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); width: 200px; height: 200px; background-color: lightgreen; }centered with absolute positioning
登录后复制
4. 使用自动保证金
对指定宽度的元素设置 margin: auto 可以使其水平居中。
例子:
center div with margin auto .container { width: 100%; height: 100vh; /* full viewport height */ display: flex; align-items: center; /* vertical center */ } .centered-div { margin: 0 auto; /* horizontal center */ width: 200px; height: 200px; background-color: lightcoral; }centered with margin auto
登录后复制
5. 使用表格显示
此方法使用 display: table 和 display: table-cell 来使元素居中。
例子:
Center Div with Table Display .container { display: table; width: 100%; height: 100vh; /* Full viewport height */ } .centered-div { display: table-cell; vertical-align: middle; /* Vertical center */ text-align: center; /* Horizontal center */ } .inner-div { display: inline-block; width: 200px; height: 200px; background-color: lightpink; }Centered with Table Display
登录后复制
拜伊
快乐编码!
以上就是在 HTML 和 CSS 中使 Div 居中的不同方法的详细内容,更多请关注【创想鸟】其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。
发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2854711.html