使用 CSS 实现水平居中是前端工程师的基本功, 在项目中经常遇到 CSS 水平居中的需求, 下面本篇文章就来给大家介绍几种 CSS 实现水平居中的方法, 希望对大家有所帮助.
方法 1, 使用 text-align: center;
使用 text-align: center; 可以将块级元素 (父元素) 中的行内元素进行水平居中; 直接给父元素设置 text-align: center; 即可.
- <style>
- #father {
- width: 500px;
- height: 300px;
- background-color: skyblue;
- text-align: center;
- }
- </style>
- <div id="father">
- <span id="son">我是行内元素</span>
- </div>
如果父元素不是块级元素, 需先将其父元素设置为块级元素, 然后在给父元素设置 text-align: center; 规则即可.
- <style>
- #father {
- display: block;
- width: 500px;
- height: 300px;
- background-color: skyblue;
- text-align: center;
- }
- </style>
- <span id="father">
- <span id="son">我是行内元素</span>
- </span>
效果图:
方法 2: 使用 margin: 0 auto;
使用 margin: 0 auto; 可以将块级元素 (父元素) 中具有固定宽度的块级元素进行水平居中; 此时需要谁居中, 就给其设置 margin: 0 auto; (作用: 使盒子自己居中).
- <style>
- #father {
- width: 500px;
- height: 300px;
- background-color: skyblue;
- }
- #son {
- width: 100px;
- height: 100px;
- background-color: green;
- margin: 0 auto;
- }
- </style>
- <div id="father">
- <div id="son">我是块级元素</div>
- </div>
效果:
方法 3: 使用定位属性
首先设置父元素为相对定位, 再设置子元素为绝对定位, 设置子元素的 left:50%, 即让子元素的左上角水平居中;
固定宽度: 设置绝对子元素的 margin-left: - 元素宽度的一半 px; 或者设置 transform: translateX(-50%);
- <style>
- #father {
- width: 500px;
- height: 300px;
- background-color: skyblue;
- position: relative;
- }
- #son {
- width: 100px;
- height: 100px;
- background-color: green;
- position: absolute;
- left: 50%;
- margin-left: -50px;
- }
- </style>
- <div id="father">
- <div id="son">我是块级元素</div>
- </div>
不定宽度: 利用 css3 新增属性 transform: translateX(-50%);
- <style>
- #father {
- width: 500px;
- height: 300px;
- background-color: skyblue;
- position: relative;
- }
- #son {
- height: 100px;
- background-color: green;
- position: absolute;
- left: 50%;
- transform: translateX(-50%);
- }
- </style>
- <div id="father">
- <div id="son">我是块级元素</div>
- </div>
效果:
方法 4: 使用 flexbox 布局实现(宽度定不定都可以)
使用 flexbox 布局, 只需要给待处理的块状元素的父元素添加属性 display: flex; justify-content: center;
- <style>
- #father {
- width: 500px;
- height: 300px;
- background-color: skyblue;
- display: flex;
- justify-content: center;
- }
- #son {
- width: 100px;
- height: 100px;
- background-color: green;
- }
- </style>
- <div id="father">
- <div id="son">我是块级元素</div>
- </div>
效果:
来源: http://www.css88.com/qa/css3/11226.html