企业网站中的图片或文字居中方法:
<center>
不建议用了。
text-align:center
在父容器里水平居中 inline 文字,或 inline 元素
vertical-align:middle
垂直居中 inline 文字,inline 元素,配合 display:table ,display:table-cell ,有奇效。
line-height
与 height 联手,垂直居中文字
margin:auto
示例:
1 2 3 4 5
|
<style> #ex2_container { width:200px; background-color:yellow; } #ex2_content { margin:0px auto; background-color:gray; color:white; display:table; } </style> <div id="ex2_container"><div id="ex2_content">Hello World</div></div>
|
hacks, hacks(小技巧)
有许多 hacks ,负 margin,影子元素 ::before 等。如果你的内容不是固定大小的话,它们大部分是很脆弱的。
translate(-50%,-50%)
用 position 加 translate translate(-50%,-50%) 比较奇特,百分比计算不是以父元素为基准,而是以自己为基准。
参考文章:居中百分比宽高的元素
示例:
1 2 3 4 5
|
<style> #ex3_container { width:200px; height:200px; background-color:yellow; position:relative; } #ex3_content { left:50%; top:50%; transform:translate(-50%,-50%); -webkit-transform:translate(-50%,-50%); background-color:gray; color:
|
|