CSS如何让盒子水平居中是前端开发中经常遇到的问题。下面介绍几种方法。
1.使用margin
.Box { width: 200px; height: 100px; margin: 0 auto; }
其中,margin:0 auto表示左右margin为0,上下margin自适应,即实现了盒子居中。
2.使用flex布局
.container { display: flex; justify-content: center; align-items: center; } .Box { width: 200px; height: 100px; }
通过设置父元素为flex布局,再设置justify-content:center和align-items:center即可实现盒子水平居中。
3.使用定位
.container { position: relative; } .Box { width: 200px; height: 100px; position: absolute; left: 50%; top: 50%; transform: translate(-50%,-50%); }
通过设置.Box为绝对定位,并通过left和top设置为50%实现了盒子的平移,在通过transform:translate(-50%,-50%)实现了盒子的居中。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。