简体   繁体   English

如何垂直对齐div内的图像

[英]How to vertically align an image inside a div

How can you align an image inside of a containing div ?如何在包含div的内部对齐图像?

Example例子

In my example, I need to vertically center the <img> in the <div> with class ="frame ":在我的示例中,我需要在<div>中使用class ="frame " 将<img>垂直居中:

<div class="frame" style="height: 25px;">
    <img src="http://jsfiddle.net/img/logo.png" />
</div>

.frame 's height is fixed and the image's height is unknown. .frame的高度是固定的,图像的高度是未知的。 I can add new elements in .frame if that's the only solution.如果这是唯一的解决方案,我可以在.frame中添加新元素。 I'm trying to do this on Internet Explorer 7 and later, WebKit, Gecko.我正在尝试在 Internet Explorer 7 及更高版本、WebKit、Gecko 上执行此操作。

See the jsfiddle here .请参阅此处的 jsfiddle。

 .frame { height: 25px; /* Equals maximum image height */ line-height: 25px; width: 160px; border: 1px solid red; text-align: center; margin: 1em 0; } img { background: #3A6F9A; vertical-align: middle; max-height: 25px; max-width: 160px; }
 <div class=frame> <img src="http://jsfiddle.net/img/logo.png" height=250 /> </div> <div class=frame> <img src="http://jsfiddle.net/img/logo.png" height=25 /> </div> <div class=frame> <img src="http://jsfiddle.net/img/logo.png" height=23 /> </div> <div class=frame> <img src="http://jsfiddle.net/img/logo.png" height=21 /> </div> <div class=frame> <img src="http://jsfiddle.net/img/logo.png" height=19 /> </div> <div class=frame> <img src="http://jsfiddle.net/img/logo.png" height=17 /> </div> <div class=frame> <img src="http://jsfiddle.net/img/logo.png" height=15 /> </div> <div class=frame> <img src="http://jsfiddle.net/img/logo.png" height=13 /> </div> <div class=frame> <img src="http://jsfiddle.net/img/logo.png" height=11 /> </div> <div class=frame> <img src="http://jsfiddle.net/img/logo.png" height=9 /> </div> <div class=frame> <img src="http://jsfiddle.net/img/logo.png" height=7 /> </div> <div class=frame> <img src="http://jsfiddle.net/img/logo.png" height=5 /> </div> <div class=frame> <img src="http://jsfiddle.net/img/logo.png" height=3 /> </div>

The only (and the best cross-browser) way as I know is to use an inline-block helper with height: 100% and vertical-align: middle on both elements.据我所知,唯一(也是最好的跨浏览器)方法是在两个元素上使用height: 100%vertical-align: middleinline-block助手。

So there is a solution: http://jsfiddle.net/kizu/4RPFa/4570/所以有一个解决方案:http: //jsfiddle.net/kizu/4RPFa/4570/

 .frame { height: 25px; /* Equals maximum image height */ width: 160px; border: 1px solid red; white-space: nowrap; /* This is required unless you put the helper span closely near the img */ text-align: center; margin: 1em 0; } .helper { display: inline-block; height: 100%; vertical-align: middle; } img { background: #3A6F9A; vertical-align: middle; max-height: 25px; max-width: 160px; }
 <div class="frame"> <span class="helper"></span><img src="http://jsfiddle.net/img/logo.png" height=250px /> </div> <div class="frame"> <span class="helper"></span><img src="http://jsfiddle.net/img/logo.png" height=25px /> </div> <div class="frame"> <span class="helper"></span><img src="http://jsfiddle.net/img/logo.png" height=23px /> </div> <div class="frame"> <span class="helper"></span><img src="http://jsfiddle.net/img/logo.png" height=21px /> </div> <div class="frame"> <span class="helper"></span><img src="http://jsfiddle.net/img/logo.png" height=19px /> </div> <div class="frame"> <span class="helper"></span> <img src="http://jsfiddle.net/img/logo.png" height=17px /> </div> <div class="frame"> <span class="helper"></span> <img src="http://jsfiddle.net/img/logo.png" height=15px /> </div> <div class="frame"> <span class="helper"></span> <img src="http://jsfiddle.net/img/logo.png" height=13px /> </div> <div class="frame"> <span class="helper"></span> <img src="http://jsfiddle.net/img/logo.png" height=11px /> </div> <div class="frame"> <span class="helper"></span> <img src="http://jsfiddle.net/img/logo.png" height=9px /> </div> <div class="frame"> <span class="helper"></span> <img src="http://jsfiddle.net/img/logo.png" height=7px /> </div> <div class="frame"> <span class="helper"></span> <img src="http://jsfiddle.net/img/logo.png" height=5px /> </div> <div class="frame"> <span class="helper"></span> <img src="http://jsfiddle.net/img/logo.png" height=3px /> </div>

Or, if you don't want to have an extra element in modern browsers and don't mind using Internet Explorer expressions, you can use a pseudo-element and add it to Internet Explorer using a convenient Expression, that runs only once per element, so there won't be any performance issues:或者,如果您不想在现代浏览器中添加额外元素并且不介意使用 Internet Explorer 表达式,则可以使用伪元素并使用方便的表达式将其添加到 Internet Explorer,每个元素仅运行一次,所以不会有任何性能问题:

The solution with :before and expression() for Internet Explorer: http://jsfiddle.net/kizu/4RPFa/4571/ Internet Explorer 的:beforeexpression()解决方案:http: //jsfiddle.net/kizu/4RPFa/4571/

 .frame { height: 25px; /* Equals maximum image height */ width: 160px; border: 1px solid red; white-space: nowrap; text-align: center; margin: 1em 0; } .frame:before, .frame_before { content: ""; display: inline-block; height: 100%; vertical-align: middle; } img { background: #3A6F9A; vertical-align: middle; max-height: 25px; max-width: 160px; } /* Move this to conditional comments */ .frame { list-style:none; behavior: expression( function(t){ t.insertAdjacentHTML('afterBegin','<span class="frame_before"></span>'); t.runtimeStyle.behavior = 'none'; }(this) ); }
 <div class="frame"><img src="http://jsfiddle.net/img/logo.png" height=250px /></div> <div class="frame"><img src="http://jsfiddle.net/img/logo.png" height=25px /></div> <div class="frame"><img src="http://jsfiddle.net/img/logo.png" height=23px /></div> <div class="frame"><img src="http://jsfiddle.net/img/logo.png" height=21px /></div> <div class="frame"><img src="http://jsfiddle.net/img/logo.png" height=19px /></div> <div class="frame"><img src="http://jsfiddle.net/img/logo.png" height=17px /></div> <div class="frame"><img src="http://jsfiddle.net/img/logo.png" height=15px /></div> <div class="frame"><img src="http://jsfiddle.net/img/logo.png" height=13px /></div> <div class="frame"><img src="http://jsfiddle.net/img/logo.png" height=11px /></div> <div class="frame"><img src="http://jsfiddle.net/img/logo.png" height=9px /></div> <div class="frame"><img src="http://jsfiddle.net/img/logo.png" height=7px /></div> <div class="frame"><img src="http://jsfiddle.net/img/logo.png" height=5px /></div> <div class="frame"><img src="http://jsfiddle.net/img/logo.png" height=3px /></div>


How it works:这个怎么运作:

  1. When you have two inline-block elements near each other, you can align each to other's side, so with vertical-align: middle you'll get something like this:当您有两个彼此靠近inline-block元素时,您可以彼此对齐,因此使用vertical-align: middle您将得到如下内容:

    两个对齐的块

  2. When you have a block with fixed height (in px , em or another absolute unit), you can set the height of inner blocks in % .当您有一个固定高度的块(以pxem或其他绝对单位为单位)时,您可以以%设置内部块的高度。

  3. So, adding one inline-block with height: 100% in a block with fixed height would align another inline-block element in it ( <img/> in your case) vertically near it.因此,在具有固定高度的块中添加一个height: 100%inline-block -block 将在其中垂直对齐其中的另一个inline-block元素(在您的情况下为<img/> )靠近它。

This might be useful:这可能有用:

div {
    position: relative;
    width: 200px;
    height: 200px;
}
img {
    position: absolute;
    top: 0;
    bottom: 0;
    margin: auto;
}
.image {
    min-height: 50px
}

matejkramny's solution is a good start, but oversized images have a wrong ratio. matejkramny 的解决方案是一个好的开始,但超大图像的比例错误。

Here's my fork:这是我的叉子:

Demo: https://jsbin.com/lidebapomi/edit?html,css,output演示: https ://jsbin.com/lidebapomi/edit?html,css,output

预习


HTML: HTML:

<div class="frame">
  <img src="foo"/>
</div>

CSS: CSS:

.frame {
    height: 160px; /* Can be anything */
    width: 160px; /* Can be anything */
    position: relative;
}
img {
    max-height: 100%;
    max-width: 100%;
    width: auto;
    height: auto;
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    margin: auto;
}

A three-line solution:三线解决方案:

position: relative;
top: 50%;
transform: translateY(-50%);

This applies to anything.这适用于任何事情。

From here .这里

A pure CSS solution:CSS 解决方案:

 .frame { margin: 1em 0; height: 35px; width: 160px; border: 1px solid red; position: relative; } img { max-height: 25px; max-width: 160px; position: absolute; top: 0; bottom: 0; left: 0; right: 0; margin: auto; background: #3A6F9A; }
 <div class=frame> <img src="http://jsfiddle.net/img/logo.png" height=250 /> </div> <div class=frame> <img src="http://jsfiddle.net/img/logo.png" height=25 /> </div> <div class=frame> <img src="http://jsfiddle.net/img/logo.png" height=23 /> </div> <div class=frame> <img src="http://jsfiddle.net/img/logo.png" height=21 /> </div> <div class=frame> <img src="http://jsfiddle.net/img/logo.png" height=19 /> </div> <div class=frame> <img src="http://jsfiddle.net/img/logo.png" height=17 /> </div> <div class=frame> <img src="http://jsfiddle.net/img/logo.png" height=15 /> </div> <div class=frame> <img src="http://jsfiddle.net/img/logo.png" height=13 /> </div> <div class=frame> <img src="http://jsfiddle.net/img/logo.png" height=11 /> </div> <div class=frame> <img src="http://jsfiddle.net/img/logo.png" height=9 /> </div> <div class=frame> <img src="http://jsfiddle.net/img/logo.png" height=7 /> </div> <div class=frame> <img src="http://jsfiddle.net/img/logo.png" height=5 /> </div> <div class=frame> <img src="http://jsfiddle.net/img/logo.png" height=3 /> </div>

Key stuff关键的东西

// position: relative; - in .frame holds the absolute element within the frame
// top: 0; bottom: 0; left: 0; right: 0; - this is key for centering a component
// margin: auto; - centers the image horizontally & vertically

For a more modern solution, and if there is no need to support legacy browsers, you can do this:对于更现代的解决方案,如果不需要支持旧版浏览器,您可以这样做:

 .frame { display: flex; /** Uncomment 'justify-content' below to center horizontally. ✪ Read below for a better way to center vertically and horizontally. **/ /* justify-content: center; */ align-items: center; } img { height: auto; /** ✪ To center this image both vertically and horizontally, in the .frame rule above comment the 'justify-content' and 'align-items' declarations, then uncomment 'margin: auto;' below. **/ /* margin: auto; */ } /* Styling stuff not needed for demo */ .frame { max-width: 900px; height: 200px; margin: auto; background: #222; } p { max-width: 900px; margin: 20px auto 0; } img { width: 150px; }
 <div class="frame"> <img src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/9988/hand-pointing.png"> </div>

Here's a Pen using Flexbox: http://codepen.io/ricardozea/pen/aa0ee8e6021087b6e2460664a0fa3f3e这是使用 Flexbox 的笔: http ://codepen.io/ricardozea/pen/aa0ee8e6021087b6e2460664a0fa3f3e

EDIT 1/13/22编辑 1/13/22

There's a better way to do this using CSS Grid and the place-content shorthand:使用 CSS Grid 和place-content速记有更好的方法:

 .frame-text-grid { display: grid; place-content: center; /** ✪ "place-content" is the shorthand for "align-content" and "justify-content". ✪ The "place-content" shorthand requires two values, the first one is for "align-content" and the second one for "justify-content". If only one value is present (like in this demo), then that single value is applied to both directions. ✪ Comment the "place-content: center;" declaration above to see how the elements are spread along the height of the container. **/ }
 <div class="ctnr frame-text-grid"> <h2>Using Grid and <code>place-content</code></h2> <p>Only two lines are needed to center vertically and horizontally.</p> </div>

Here's a Pen using CSS Grid: https://codepen.io/ricardozea/pen/c4e27f1e74542618d73e21f7c2276272?editors=0100这是使用 CSS Grid 的钢笔: https ://codepen.io/ricardozea/pen/c4e27f1e74542618d73e21f7c2276272?editors=0100

This way you can center an image vertically ( demo ):这样,您可以垂直居中图像(演示):

div{
  height: 150px; // Internet Explorer 7 fix
  line-height: 150px;
}
img{
  vertical-align: middle;
  margin-bottom: 0.25em;
}

Also, you can use Flexbox to achieve the correct result:此外,您可以使用 Flexbox 来获得正确的结果:

 .parent { align-items: center; /* For vertical align */ background: red; display: flex; height: 250px; /* justify-content: center; <- for horizontal align */ width: 250px; }
 <div class="parent"> <img class="child" src="https://cdn2.iconfinder.com/data/icons/social-icons-circular-black/512/stackoverflow-128.png" /> </div>

There is a super easy solution with flexbox! flexbox有一个超级简单的解决方案!

.frame {
    display: flex;
    align-items: center;
}

Imagine you have想象一下你有

<div class="wrap">
    <img src="#">
</div>

And css:和CSS:

.wrap {
    display: flex;
}
.wrap img {
    object-fit: contain;
}

CSS Grid CSS 网格

If you want to align a single image vertically inside an image container you can use this:如果要在图像容器内垂直对齐单个图像,可以使用:

.img-container {
  display: grid;
}

img { 
  align-self: center;
}

 .img-container { display: grid; grid-auto-flow: column; background: #BADA55; width: 1200px; height: 500px; } img.vertical-align { align-self: center; }
 <div class="img-container"> <img src="https://picsum.photos/300/300" /> <img class="vertical-align" src="https://picsum.photos/300/300" /> <img src="https://picsum.photos/300/300" /> </div>

If you want to align multiple images inside an image container you can use this:如果你想在一个图像容器内对齐多个图像,你可以使用这个:

.img-container {
  display: grid;
  align-items: center;
}

 .img-container { display: grid; grid-auto-flow: column; align-items: center; background: #BADA55; width: 1200px; height: 500px; }
 <div class="img-container"> <img src="https://picsum.photos/300/300" /> <img src="https://picsum.photos/300/300" /> <img src="https://picsum.photos/300/300" /> </div>

Please note that I have used grid-auto-flow: column in both the cases because otherwise the elements wrap to a row with specifying explicit grid items.请注意,我在这两种情况下都使用了grid-auto-flow: column ,因为否则元素将换行并指定明确的网格项。 In the question code, I see the item centered horizontally too.在问题代码中,我也看到该项目水平居中。 In that case, just make use of the place-items: center instead of align-items: center .在这种情况下,只需使用place-items: center而不是align-items: center

You could try setting the CSS of PI to display: table-cell; vertical-align: middle;您可以尝试将 PI 的 CSS 设置为display: table-cell; vertical-align: middle; display: table-cell; vertical-align: middle;

You can try the below code:你可以试试下面的代码:

 .frame{ display: flex; justify-content: center; align-items: center; width: 100%; }
 <div class="frame" style="height: 25px;"> <img src="http://jsfiddle.net/img/logo.png" /> </div>

Background image solution背景图片解决方案

I removed the image element altogether and set it as background of the div with a class of .frame我完全删除了图像元素并将其设置为具有.frame类的 div 的背景

http://jsfiddle.net/URVKa/2/ http://jsfiddle.net/URVKa/2/

This at least works fine on Internet Explorer 8, Firefox 6 and Chrome 13.这至少在 Internet Explorer 8、Firefox 6 和 Chrome 13 上运行良好。

I checked, and this solution will not work to shrink images larger than 25 pixels height.我查了一下,这个解决方案不能缩小大于 25 像素高度的图像。 There is a property called background-size which does set the size of the element, but it is CSS 3 which would conflict with Internet Explorer 7 requirements.有一个名为background-size的属性确实设置了元素的大小,但它是 CSS 3,它会与 Internet Explorer 7 的要求相冲突。

I would advice you to either redo your browser priorities and design for the best available browsers, or get some server-side code to resize the images if you'd want to use this solution.如果您想使用此解决方案,我建议您重做浏览器优先级并设计最佳可用浏览器,或者获取一些服务器端代码来调整图像大小。

http://jsfiddle.net/MBs64/ http://jsfiddle.net/MBs64/

.frame {
    height: 35px;      /* Equals maximum image height */
    width: 160px;
    border: 1px solid red;
    text-align: center;
    margin: 1em 0;
    display: table-cell;
    vertical-align: middle;
}
img {
    background: #3A6F9A;
    display: block;
    max-height: 35px;
    max-width: 160px;
}

The key property is display: table-cell;关键属性是display: table-cell; for .frame .对于.frame Div.frame is displayed as inline with this, so you need to wrap it in a block element. Div.frame显示为内联,因此您需要将其包装在块元素中。

This works in Firefox, Opera, Chrome, Safari and Internet Explorer 8 (and later).这适用于 Firefox、Opera、Chrome、Safari 和 Internet Explorer 8(及更高版本)。

UPDATE更新

For Internet Explorer 7 we need to add a CSS expression:对于 Internet Explorer 7,我们需要添加一个 CSS 表达式:

*:first-child+html img {
    position: relative;
    top: expression((this.parentNode.clientHeight-this.clientHeight)/2+"px");
}

You could do this:你可以这样做:

Demo演示

http://jsfiddle.net/DZ8vW/1 http://jsfiddle.net/DZ8vW/1

CSS CSS

.frame {
    height: 25px;      /* Equals maximum image height */
    line-height: 25px;
    width: 160px;
    border: 1px solid red;
    
    text-align: center; 
    margin: 1em 0;
    position: relative; /* Changes here... */
}
img {
    background: #3A6F9A;
    max-height: 25px;
    max-width: 160px;
    top: 50%;           /* Here.. */
    left: 50%;          /* Here... */
    position: absolute; /* And here */
}    

JavaScript JavaScript

$("img").each(function(){
    this.style.marginTop = $(this).height() / -2 + "px";
})

This works for modern browsers (2016 at time of edit) as shown in this demo on codepen这适用于现代浏览器(编辑时为 2016 年),如codepen 上的演示中所示

.frame {
    height: 25px;
    line-height: 25px;
    width: 160px;
    border: 1px solid #83A7D3;          
}
.frame img {
    background: #3A6F9A;
    display:inline-block;
    vertical-align: middle;
}

It is very important that you either give the images a class or use inheritance to target the images that you need centered.给图像一个类或使用继承来定位您需要居中的图像是非常重要的。 In this example we used .frame img {} so that only images wrapped by a div with a class of .frame would be targeted.在这个例子中,我们使用了.frame img {} ,因此只有被.frame类的 div 包裹的图像才会被定位。

Solution using a table and table cells使用表格和表格单元格的解决方案

Sometimes it should be solved by displaying as table/table-cell.有时应该通过显示为表格/表格单元格来解决。 For example, a fast title screen.例如,快速标题屏幕。 It is a recommended way by W3 also.这也是 W3 推荐的方式。 I recommend you check this link called Centering a block or image from W3C.org.我建议你查看这个链接,名为Centering a block or image from W3C.org。

The tips used here are:这里使用的技巧是:

  • Absolute positioning container displayed as table绝对定位容器显示为表格
  • Vertical aligned to center content displayed as table-cell垂直对齐到显示为表格单元格的中心内容

 .container { position: absolute; display: table; width: 100%; height: 100%; } .content { display: table-cell; vertical-align: middle; }
 <div class="container"> <div class="content"> <h1 style="text-align:center">Peace in the world</h1> </div> </div>

Personally I actually disagree about use helpers for this purpose.就我个人而言,我实际上不同意为此目的使用助手。

My solution: http://jsfiddle.net/XNAj6/2/我的解决方案:http: //jsfiddle.net/XNAj6/2/

<div class="container">
    <div class="frame">
        <img src="http://jsfiddle.net/img/logo.png" class="img" alt="" />
    </div>
</div>

.container {
    display: table;
    float: left;
    border: solid black 1px;
    margin: 2px;
    padding: 0;
    background-color: black;
    width: 150px;
    height: 150px;
}
.frame {
    display: table-cell;
    text-align: center;
    vertical-align: middle;
    border-width: 0;
}
.img {
    max-width: 150px;
    max-height: 150px;
    vertical-align: middle;
}

I am not sure about Internet Explorer, but under Firefox and Chrome, if you have an img in a div container, the following CSS content should work.我不确定 Internet Explorer,但在 Firefox 和 Chrome 下,如果您在div容器中有img ,则以下 CSS 内容应该可以工作。 At least for me it works well:至少对我来说效果很好:

div.img-container {
    display: table-cell;
    vertical-align: middle;
    height: 450px;
    width: 490px;
}

div.img-container img {
    max-height: 450px;
    max-width: 490px;
}

Try this solution with pure CSS http://jsfiddle.net/sandeep/4RPFa/72/使用纯 CSS http://jsfiddle.net/sandeep/4RPFa/72/尝试此解决方案

Maybe it is the main problem with your HTML.也许这是您的 HTML 的主要问题。 You're not using quotes when you define c lass & image height in your HTML.当您在 HTML 中定义 c lassimage height时,您没有使用引号。

CSS: CSS:

.frame {
    height: 25px;      /* Equals maximum image height */
    width: 160px;
    border: 1px solid red;
    position: relative;
    margin: 1em 0;
    top: 50%;
    text-align: center;
    line-height: 24px;
    margin-bottom: 20px;
}

img {
    background: #3A6F9A;
    vertical-align: middle;
    line-height: 0;
    margin: 0 auto;
    max-height: 25px;
}

When I work around with the img tag it's leaving 3 pixels to 2 pixels space from top .当我使用img标签时,它会从top留下 3 像素到 2 像素的空间。 Now I decrease line-height , and it's working.现在我减少line-height ,它正在工作。

CSS: CSS:

    .frame {
        height: 25px;      /* Equals maximum image height */
        width: 160px;
        border: 1px solid red;
        margin: 1em 0;
        text-align: center;
        line-height: 22px;
        *:first-child+html line-height:24px; /* For Internet Explorer 7 */
    }

    img {
        background: #3A6F9A;
        vertical-align: middle;
        line-height: 0;    
        max-height: 25px;
        max-width: 160px;
    }
@media screen and (-webkit-min-device-pixel-ratio:0) {
    .frame {
        line-height:20px; /* WebKit browsers */
    }

The line-height property is rendered differently in different browsers. line-height属性在不同浏览器中的呈现方式不同。 So, we have to define different line-height property browsers.所以,我们必须定义不同line-height属性浏览器。

Check this example: http://jsfiddle.net/sandeep/4be8t/11/检查这个例子:http: //jsfiddle.net/sandeep/4be8t/11/

Check this example about line-height different in different browsers: input height differences in Firefox and Chrome检查此示例,了解不同浏览器中line-height不同: Firefox 和 Chrome 中的输入高度差异

An easy way which work for me:一种对我有用的简单方法:

img {
    vertical-align: middle;
    display: inline-block;
    position: relative;
}

It works for Google Chrome very well.它非常适用于谷歌浏览器。 Try this one out in a different browser.在不同的浏览器中试试这个。

For centering an image inside a container (it could be a logo) besides some text like this:除了像这样的一些文本之外,用于在容器内居中图像(可能是徽标):

在此处输入图像描述

Basically you wrap the image基本上你包装图像

 .outer-frame { border: 1px solid red; min-height: 200px; text-align: center; /* Only to align horizontally */ } .wrapper{ line-height: 200px; border: 2px dashed blue; border-radius: 20px; margin: 50px } img { /* height: auto; */ vertical-align: middle; /* Only to align vertically */ }
 <div class="outer-frame"> <div class="wrapper"> some text <img src="http://via.placeholder.com/150x150"> </div> </div>

I had the same problem.我有同样的问题。 This works for me:这对我有用:

<style type="text/css">
    div.parent {
        position: relative;
    }

    img.child {
        bottom: 0;
        left: 0;
        margin: auto;
        position: absolute;
        right: 0;
        top: 0;
    }
</style>

<div class="parent">
    <img class="child">
</div>

If you can live with pixel-sized margins, just add font-size: 1px;如果您可以忍受像素大小的边距,只需添加font-size: 1px; to the .frame ..frame But remember, that now on the .frame 1em = 1px, which means, you need to set the margin in pixels too.但请记住,现在在.frame 1em = 1px 上,这意味着您还需要以像素为单位设置边距。

http://jsfiddle.net/feeela/4RPFa/96/ http://jsfiddle.net/feeela/4RPFa/96/

Now it's not centered any more in Opera…现在它不再以 Opera 为中心了……

You can use this:你可以使用这个:

 .loaderimage {
    position: absolute;
    top: 50%;
    left: 50%;
    width: 60px;
    height: 60px;
    margin-top: -30px; /* 50% of the height */
    margin-left: -30px;
 }

Want to align an image which have after a text / title and both are inside a div?想要对齐在文本/标题之后且都在 div 内的图像?

See on JSfiddle or Run Code Snippet.请参阅JSfiddle或运行代码片段。

Just be sure to have an ID or a class at all your elements (div, img, title, etc.).只要确保所有元素(div、img、title 等)都有一个 ID 或一个类。

For me works this solution on all browsers (for mobile devices you must to adapt your code with: @media).对我来说,此解决方案适用于所有浏览器(对于移动设备,您必须使用:@media 调整您的代码)。

 h2.h2red { color: red; font-size: 14px; } .mydivclass { margin-top: 30px; display: block; } img.mydesiredclass { margin-right: 10px; display: block; float: left; /* If you want to allign the text with an image on the same row */ width: 100px; heght: 100px; margin-top: -40px /* Change this value to adapt to your page */; }
 <div class="mydivclass"> <br /> <img class="mydesiredclass" src="https://upload.wikimedia.org/wikipedia/commons/thumb/b/b3/Wikipedia-logo-v2-en.svg/2000px-Wikipedia-logo-v2-en.svg.png"> <h2 class="h2red">Text aligned after image inside a div by negative manipulate the img position</h2> </div>

Using table and table-cell method do the job, specially because you targeting some old browsers as well, I create a snippet for you which you can run it and check the result:使用tabletable-cell方法完成这项工作,特别是因为您也针对一些旧浏览器,我为您创建了一个片段,您可以运行它并检查结果:

 .wrapper { position: relative; display: table; width: 300px; height: 200px; } .inside { vertical-align: middle; display: table-cell; }
 <div class="wrapper"> <div class="inside"> <p>Centre me please!!!</p> </div> <div class="inside"> <img src="https://cdn2.iconfinder.com/data/icons/social-icons-circular-black/512/stackoverflow-128.png" /> </div> </div>

Just for the sake of this being a valid answer I still want to post the jQuery solution again.只是为了这是一个有效的答案,我仍然想再次发布 jQuery 解决方案。 This works for every element that has the v_align class applied to it.这适用于每个应用了v_align类的元素。 It will be vertical centered in the parent and on resizing of the window it will be recalculated.它将在父级中垂直居中,并且在调整窗口大小时将重新计算。

Link to the JSFiddle链接到 JSFiddle

$(document).ready(function() {
  // Define the class that vertically aligns stuff
  var objects = '.v_align';
  // initial setup
  verticalAlign(objects);

  // Register resize event listener
  $(window).resize(function() {
    verticalAlign(objects);
  });
});

function verticalAlign(selector) {
  $(selector).each(function(val) {
    var parent_height = $(this).parent().height();
    var dif = parent_height - $(this).height()
    // Should only work if the parent is larger than the element
    var margin_top = dif > 0 ? dif/2 : 0;
    $(this).css("margin-top", margin_top + "px");
  });
}

The best solution is that最好的解决方案是

.block{
    /* Decor */
    padding:0 20px;
    background: #666;
    border: 2px solid #fff;
    text-align: center;
    /* Important */
    min-height: 220px;
    width: 260px;
    white-space: nowrap;
}
.block:after{
    content: '';
    display: inline-block;
    height: 220px; /* The same as min-height */
    width: 1px;
    overflow: hidden;
    margin: 0 0 0 -5px;
    vertical-align: middle;
}
.block span{
    vertical-align: middle;
    display: inline-block;
    white-space: normal;
}

I have been playing around with using padding for center alignment.我一直在使用填充来进行中心对齐。 You will need to define the top level outer-container size, but the inner container should resize, and you can set the padding at different percentage values.您将需要定义顶级外部容器大小,但内部容器应该调整大小,并且您可以将填充设置为不同的百分比值。

jsfiddle jsfiddle

<div class='container'>
  <img src='image.jpg' />
</div>

.container {
  padding: 20%;
  background-color: blue;
}

img {
  width: 100%;
}

Use this one:使用这个:

position: absolute;
top: calc(50% - 0.5em);
left: calc(50% - 0.5em);
line-height: 1em;

And you can vary font-size .你可以改变font-size

This code work well for me.这段代码对我很有效。

<style>
    .listing_container{width:300px; height:300px;font: 0/0 a;}
    .listing_container:before { content: ' ';display: inline-block;vertical-align: bottom;height: 100%;}
    .listing_container img{ display: inline-block; vertical-align: middle;font: 16px/1 Arial sans-serif; max-height:100%; max-width:100%;}
<style>

<div class="listing_container">
    <img src="http://www.advancewebsites.com/img/theme1/logo.png">
</div>

I add a new solution to this old question because I see that my preferred method is not included in the answers.我为这个老问题添加了一个新的解决方案,因为我发现我的首选方法未包含在答案中。

In every project, at the very beginning, I create 2 CSS classes在每个项目中,一开始,我都会创建 2 个 CSS 类

.flex-centered {
    display: flex; 
    flex-direction-column; 
    justify-content:center
}
.abs-centered {
    position: absolute; 
    top: 50%; 
    left: 50%; 
    transform: translate(-50%, -50%)
}

You can center elements with both, depending on the situation.您可以根据情况将两者都居中。

flex-centered is more versatile for images and content on the page, abs-centered need a relative parent is good for centered div, like popups. flex-centered 对于页面上的图像和内容更加通用,abs-centered 需要一个相对父级对于居中的 div 来说是好的,比如弹出窗口。

So you just call所以你只要打电话

   <div class='flex-centered'>
        <img>
    </div>

and the image is vertically centered.并且图像垂直居中。

 .flex-centered { display: flex; flex-direction: column; justify-content: center; } /* this to center horizontally, too */ .m0a { margin: 0 auto } /* Make a big parent grey */ .big-div { height:200px; width: 200px; background:#ccc; border-radius: 4px; } /* Make a small div to be centered */ .small-div { height:20px; width:20px; background:red; }
 <div class="flex-centered big-div" > <div class="small-div m0a"></div> </div>

You can use table structure inside a div您可以在 div 中使用表结构

<div class="frame">
     <table width="100%">
         <tr>
            <td vertical-align="middle" align="center" height="25">
                <img src="https://jsfiddle.net/img/logo.png" >  
            </td>
        </tr>
    </table>
</div>

You can use a grid layout to vertically center the image.您可以使用grid布局将图像垂直居中。

.frame {
  display: grid;
  grid-template-areas: "."
                       "img"
                       "."
  grid-template-rows: 1fr auto 1fr;
  grid-template-columns: auto;
}
.frame img {
  grid-area: img;
}

This will create a 3 row 1 column grid layout with unnamed 1 fraction wide spacers at the top and bottom, and an area named img of auto height (size of the content).这将创建一个 3 行 1 列的网格布局,在顶部和底部具有未命名的 1 个分数宽的间隔,以及一个名为imgauto高度(内容大小)的区域。

The img will use the space it prefers, and the spacers at top and bottom will use the remaining height split to two equal fractions, resulting in the img element to be vertically centered. img将使用它喜欢的空间,顶部和底部的垫片将使用剩余的高度分成两个相等的分数,从而使img元素垂直居中。

http://jsfiddle.net/Kissaki0/4RPFa/20713/ http://jsfiddle.net/Kissaki0/4RPFa/20713/

I was looking for a similar answer and some of the suggestions snapped the image to the left or the vertical ratio squashed the image, so I came up with this solution... It centers the content vertically and horizontally.我一直在寻找类似的答案,并且一些建议将图像向左对齐或垂直比例压扁了图像,所以我想出了这个解决方案......它将内容垂直和水平居中。

 .div{
    position: relative;
    overflow: hidden;
 }
 .bantop img {
    position: absolute;
    margin: auto;
    width: 103%;
    height: auto;
    top: -50%;
    bottom: -50%;
    left: -50%;
    right: -50%;
  }

I use it on several projects and it works like a charm.我在几个项目中使用它,它就像一个魅力。

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

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