text-aling: center;
,父元素宽度不管肯定不肯定,都可实现相对于父元素水平居中。<style> .box { border:1px solid #aaa; text-align: center; /* text-align定义行内内容相对于父元素如何对齐 */ } img { width:100px; } </style> </head> <body> <div class="box"> <img src="http://static.jsbin.com/images/dave.min.svg" alt=""> </div> </body>
<style> .box { border:1px solid #aaa; width:300px; } .son { height: 200px; width:100px; border: 1px solid; margin: 0 auto; /* 子元素进行外边距设置 */ } </style> </head> <body> <div class="box"> <div class="son"></div> </div> </body>
效果和上图同样svg
对于块级元素来讲,它的高度在没有显示设置的状况下,是由子元素高度撑开的,因此对于子元素是内联元素的能够采起对父元素进行设置padding来进行垂直居中布局
<style> .box { border:1px solid #aaa; width:100px; font-size: 14px; word-break:break-all; /* line-height: 2em; */ padding: 14px; } </style> </head> <body> <div class="box"> <span>aaaaaaaaaaaaaaaaaafaddadfadfadfadfdfadfadfadfdfadafadfagadgadfadferew</span> </div>
子元素宽高肯定flex
使用子元素margin进行居中spa
<style> .box { border:1px solid #aaa; width:400px; height: 400px; } .son { height: 100px; width: 100px; border: 1px solid; /* 代码以下 */ margin-left: calc(50% - 50px); margin-top: calc(50% - 50px); } </style> </head> <body> <div class="box"> <div class="son"></div> </div>
子元素宽高不肯定code
使用定位加margin 居中orm
<style> .box { border:1px solid #aaa; width:400px; height: 400px; position: relative; } .son { height: 100px; width: 100px; border: 1px solid; /* 代码以下 */ position: absolute; top: 0; bottom: 0; left: 0; right: 0; margin: auto; } </style> </head> <body> <div class="box"> <div class="son"></div> </div>
使用transform 来实现居中图片
<style> .box { border:1px solid #aaa; width:400px; height: 400px; position: relative; } .son { height: 100px; width: 100px; border: 1px solid; /* x、y 轴 平移50% */ position: absolute; top: 50%; left: 50%; transform: translate(-50%,-50%); } </style> </head> <body> <div class="box"> <div class="son"></div> </div>
当子元素是一个图片时,父元素使用text-align:center; 子元素设置vertical-align: middle;,且用父元素的伪元素等同父元素高度后设置为vertical-align:middle;rem
<style> .box { border:1px solid #aaa; width:400px; height: 400px; text-align: center; } .box::after {content:''; display: inline-block; height:100%; vertical-align:middle; } img { height: 100px; vertical-align:middle; } </style> </head> <body> <div class="box"> <img src="http://static.jsbin.com/images/dave.min.svg" alt=''> </div>
对父元素设置为table-cell来实现居中,须要设置宽高it
<style> .box { border:1px solid #aaa; width:400px; height: 400px; display: table-cell; vertical-align:middle; text-align:center; } img { height: 100px; } </style> </head> <body> <div class="box"> <img src="http://static.jsbin.com/images/dave.min.svg" alt=''> </div>
flex 布局,使用主轴和侧轴的对齐方式来实现居中io
<style> .box { border:1px solid #aaa; width:400px; height: 400px; display: flex; justify-content: center; /* 主轴对齐方式 */ align-items: center; /* 交叉轴对齐方式 */ } img { height: 100px; } </style> </head> <body> <div class="box"> <img src="http://static.jsbin.com/images/dave.min.svg" alt=''> </div> </body>
若有错漏,欢迎指正。