Html 如何将包裹在 SPAN 标签中的 img 居中对齐?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11370592/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to center align img wrapped in SPAN tag?
提问by JROB
I am trying to center align an image that is wrapped in a <span>
, but I am having trouble doing so. I have uploaded my CSS and HTML to jsfiddle: http://jsfiddle.net/7nHhu/1/
我正在尝试将包裹在 a 中的图像居中对齐<span>
,但我在这样做时遇到了麻烦。我已将 CSS 和 HTML 上传到 jsfiddle:http: //jsfiddle.net/7nHhu/1/
I am trying to get the image to center align itself with the content in a "block" style (ie. all text above and below it, not wrapped to the left or right)
我试图让图像以“块”样式将自己与内容居中对齐(即,它上面和下面的所有文本,而不是向左或向右包裹)
Any help would be greatly appreciated.
任何帮助将不胜感激。
.imgframe {
border: 1px solid #EAEAEA;
display: inline-block;
margin: 8px;
}
.imgframe img {
border: 1px solid #FFFFFF;
margin: 0;
background: #F6F6F6;
padding: 8px;
-moz-box-shadow: 2px 2px 5px #CCCCCC;
-webkit-box-shadow: 2px 2px 5px #CCCCCC;
}
<span class="imgframe centerimg"><img src="http://i48.tinypic.com/31368e9.jpg" /></span>?
采纳答案by Musa
回答by Foreever
I think it's more appropriate to use text-align for centering text rather than images. You could center an image by setting left and right margin auto.
我认为使用 text-align 来居中文本而不是图像更合适。您可以通过设置左右边距自动使图像居中。
img {
display: block;
margin-left: auto;
margin-right: auto;
height: auto;
padding-top: 10px; //margin-top doesn't work
}
回答by David says reinstate Monica
Given your requirements, to keep the .imgframe
element in-line, to avoid it taking up the full width of the enclosing element, and working without adding wrapping elements to your mark-up, the following works:
根据您的要求,为了保持.imgframe
元素内联,避免它占据封闭元素的整个宽度,并且在不向标记中添加包装元素的情况下工作,以下工作:
body {
text-align: center;
}
body p {
text-align: left;
}
This would, probably, be less intrusive if you had the elements from your Fiddle wrapped in a specific, target-able, element; rather than the body
, as the method, above, requires you to reset the text-align
for all elements contained within the body
. So, personally, I'd use:
如果您将 Fiddle 中的元素包装在特定的、可定位的元素中,这可能会减少干扰;而不是body
,因为上面的方法要求您为 中text-align
包含的所有元素重置body
。所以,就个人而言,我会使用:
<div id="contentWrapper">
<p>...</p>
<span class="imgframe">
<img src="..." />
</span>
<p>...</p>
</div>
And:
和:
#contentWrapper {
text-align: center;
}
#contentWrapper p {
text-align: left;
}
Just in order to minimise the amount of work required to tidy up afterwards.
只是为了尽量减少事后整理所需的工作量。
回答by TheGeekYouNeed
In .imgframe, add width: 100%;
在 .imgframe 中,添加宽度:100%;
回答by uyghurbeg
span {position: absolute; top:0; left: 0; width: 100%; text-align: center;}
img {width:yourimagewidth; heigth: width:yourimageheigth}