如何在没有固定宽度的图像中居中

时间:2022-04-24 20:28:04

I am trying to center images that will not have a fixed width as its a gallery with various image sizes so cannot use margin 0 auto as you need a fixed width for that.

我想把没有固定宽度的图像居中,因为它是一个有不同图像大小的图库,所以不能使用空白0自动,因为你需要一个固定的宽度。

Is there a jquery solution?

是否有jquery解决方案?

3 个解决方案

#1


6  

Use this to center the images:

用这个来居中图像:

.wrapper { /* your wrapper element */
    text-align:center;   
}
.wrapper img {
    display:inline-block;   
}

However, if the images are small enough in width to go side-by-side and fit in the wrapper, they will. You can get around this with extra markup like wrapper <div>s around the image or even <br />.

但是,如果图像的宽度足够小,可以并排放置在包装中,那么它们就会这样做。您可以使用额外的标记,比如包装器

s,甚至

Demo: http://jsfiddle.net/wesley_murch/Cwed9/1/

演示:http://jsfiddle.net/wesley_murch/Cwed9/1/

Make sure to adjust the width in the demo to see what I mean.

确保调整演示中的宽度,以了解我的意思。

EDIT: I was playing jsfiddle while this was answered in the comments :P

编辑:我在玩jsfiddle,而在注释中有这样的回答:P

#2


0  

Hmm --

嗯——

Are you saying the image is too large for the canvas? If so... have the canvas overflow:hidden;

你是说这幅画对画布来说太大了吗?如果是这样的话……画布溢出:隐藏;

if (image-width > canvas-width){
   offset = image-width - canvas-width;
   offset = offset / 2;
   image.left = -offset;
}

#3


0  

try with this style

试着用这个风格

HTML

<div>
    <img src="" height="155px" width="155px" style="float:left">
</div>

CSS

img {  
    display: table-cell; // this says treat this element like a table cell
    vertical-align:middle;   
}

#1


6  

Use this to center the images:

用这个来居中图像:

.wrapper { /* your wrapper element */
    text-align:center;   
}
.wrapper img {
    display:inline-block;   
}

However, if the images are small enough in width to go side-by-side and fit in the wrapper, they will. You can get around this with extra markup like wrapper <div>s around the image or even <br />.

但是,如果图像的宽度足够小,可以并排放置在包装中,那么它们就会这样做。您可以使用额外的标记,比如包装器

s,甚至

Demo: http://jsfiddle.net/wesley_murch/Cwed9/1/

演示:http://jsfiddle.net/wesley_murch/Cwed9/1/

Make sure to adjust the width in the demo to see what I mean.

确保调整演示中的宽度,以了解我的意思。

EDIT: I was playing jsfiddle while this was answered in the comments :P

编辑:我在玩jsfiddle,而在注释中有这样的回答:P

#2


0  

Hmm --

嗯——

Are you saying the image is too large for the canvas? If so... have the canvas overflow:hidden;

你是说这幅画对画布来说太大了吗?如果是这样的话……画布溢出:隐藏;

if (image-width > canvas-width){
   offset = image-width - canvas-width;
   offset = offset / 2;
   image.left = -offset;
}

#3


0  

try with this style

试着用这个风格

HTML

<div>
    <img src="" height="155px" width="155px" style="float:left">
</div>

CSS

img {  
    display: table-cell; // this says treat this element like a table cell
    vertical-align:middle;   
}