简体   繁体   English

在DIV中居中对齐图像

[英]Center align image within DIV

Although this question is asked before, my problem is little different. 虽然之前提出过这个问题,但我的问题却没有什么不同。 I have a div, within which I have two images. 我有一个div,其中我有两个图像。 First image needs to be stayed left align, where as the second image needs to be center aligned. 第一个图像需要保持左对齐,其中第二个图像需要居中对齐。 The div has no fixed width, so that it covers the heading. div没有固定的宽度,因此它覆盖了标题。 I have created a fiddle, which can be found here . 我创造了一个小提琴,可以在这里找到。

Any suggestion will be very helpful to me. 任何建议都对我很有帮助。

Case 1 情况1

Add text-align:center to the div class. text-align:center添加到div类。

Give float:left to the first image by using pseudo class so that your second image will be center aligned to the div and first image will be left aligned. 使用伪类给float:left第一个图像,这样第二个图像将与div居中对齐,第一个图像将保持对齐。

Here is the demo http://jsfiddle.net/Eevpc/5/ 这是演示http://jsfiddle.net/Eevpc/5/

Case 2 案例2

Do it by position:absolute position:absolute

.brandLogo {
    margin: 15px; background-color:red; text-align:center; position:relative;
}   

a img:first-child {
    border: 0 none; position: absolute; left:0;
    height: auto;
    vertical-align: middle;
}
img {
    border: 0 none; margin:0 auto !important;
    height: auto;
    vertical-align: middle;
}

Demo http://jsfiddle.net/Eevpc/11/ 演示http://jsfiddle.net/Eevpc/11/

In case 1, second image is center for the remaining width of the div (ignoring the space occupied by the first image). 在情况1中,第二图像是div的剩余宽度的中心(忽略第一图像占据的空间)。

In case 2, second image is aligned to the exact center of the original div width. 在情况2中,第二图像与原始div宽度的精确中心对齐。

Hope this will work. 希望这会奏效。

.div_class{
   display: block;
   margin-left: auto;
   margin-right: auto;
}

Thanks 谢谢

Try this: 尝试这个:

<div id="main" style="text-align:center; width:100%;">
  <div id="left" style="float:left;">
    <img src="..." alt="..."/>
  </div>
  <div id="right" style="float:right; width:100%; text-align:center;">
    <img src="..." alt="..." style="margin:0 auto;" />
  </div>
  <div style="clear:both; content:'.'; display:none" />
</div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM