簡體   English   中英

水平對齊大於其父DIV的圖像

[英]Horizontally align image that's bigger than its parent DIV

我正在一個自適應網站上工作,我想水平居中放置比父DIV寬的圖像。 圖像與其父圖像具有相同的高度。 圖像的寬度與高度成比例,因此可以正確渲染。 我無法將圖像設置為背景圖像。

如何將圖像水平居中? 最好使用CSS,即使使用jQuery也可以。

<div>
    <img src="...">
</div>

.div {
    height: 220px;
    margin: 0;
    position: relative;
    width: 100%;
}

.div img {
    display: block;
    height: inherit;
    margin: auto;
    max-width: none;
    width: initial;
}

使圖像居中的簡單方法是結合使用絕對位置和負位置translateX:

.div img {
    display: block;
    height: inherit;
    margin: auto;
    max-width: none;
    width: initial;
    position: absolute;
    left: 50%;
    -webkit-transform: translateX(-50%);
    transform: translateX(-50%);
}

演示: http //jsfiddle.net/fa000nkw/

看看這些柔韌性盒屬性是否有幫助...

 justify-content: center;

 align-items: center;

也可以嘗試使用display:flex; 或顯示:inline-flex; 如果需要的話。

是的,就像魅力一樣...

.div {
   background: #AAA;
   height: 220px;
   position: absolute;
   width: 100%;
   overflow: hidden;
   justify-content: center;
   align-items: center;
   display:flex;
}
.div img {
  display:flex;
  height: 100%;
  position: relative;
  width: initial;
  justify-content: center;
  align-items: center;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM