为了生成 filter 属性,使用了以下资源:IE 的 CSS3 转换转换器示例.box {边距:10px;显示:内联块;位置:相对;}.box 跨度 {位置:绝对;顶部:50%;左:50%;背景:#fff;box-shadow: 0 0 3px rgba(0, 0, 0, 1);填充:5px;}.box.translate >跨度 {变换:翻译(-50%,-50%);-ms-filter: "progid:DXImageTransform.Microsoft.Matrix(M11=1, M12=0, M21=0, M22=1, SizingMethod='auto expand')";}<img src="http://placehold.it/500x200"/><span>居中文本</span>I don't even know if this is possible using CSS only, but I have to ask.PLEASE, read the specs before you provide an answer, accordingly. Thank you!My markup:<div class="wrapper"> <img src="http://placehold.it/350x150"> <p>Some text random size</p></div>Obviously, .wrapper will have the height of my img element, if that's a block.Then, I need the p element to be centered horizontally and vertically inside the wrapper. I don't have a fixed width or height for the p element.So, regardless paragraph size or even image size, it should be vertically and horizontally aligned, as is shown here http://i.imgur.com/phiR48H.png or here http://i.imgur.com/Xvdt42j.png.If I set absolute position on the paragraph, it will not vertically align, because I cannot set negative margin if I don't know paragraph height.I was thinking about table and table-cell (vertical-align: middle;), but I only have 1 cell. Any thoughts?Added fiddle: http://jsfiddle.net/f3x7977z/It's important that the provided solution have backwards compatibility, in special in IE8+.Any suggestions on extra wrappers, for the sake of the final result, are welcome! 解决方案 ExplanationChange the CSS property position of the wrapper to relative and of element you want centered to absolute.Then position the element in the middle of the wrapper using top: 50% and left: 50%.After this you will notice that the element is not exactly centered, because it's own height and width are off the calculation.So we fix with the property transform: translate(-50%, -50%), which brings the element half of it's height up, and half it's width left. The result will be a vertically and horizontally centered element.Since we are taking IE8 into consideration, we will use a filter to achieve the same effect as the transform: translate.In order to generate the filter attribute, the following resource was used: IE's CSS3 Transforms TranslatorExample.box { margin: 10px; display: inline-block; position: relative;}.box span { position: absolute; top: 50%; left: 50%; background: #fff; box-shadow: 0 0 3px rgba(0, 0, 0, 1); padding: 5px;}.box.translate > span { transform: translate(-50%, -50%); -ms-filter: "progid:DXImageTransform.Microsoft.Matrix(M11=1, M12=0, M21=0, M22=1, SizingMethod='auto expand')";}<div class="box translate"> <img src="http://placehold.it/500x200" /> <span>centered text</span></div> 这篇关于在不知道大小的情况下水平和垂直居中绝对定位元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 08-31 02:27