2015-03-31 119 views
0

JSFiddle將div設置爲子圖像的寬度和高度?

我有一個容器類的div。這個div的高度必須等於寬度。我已經實現了這一點:

.container{ 
    background-color: #e6e6e6; 
    position: relative; 
} 

.container:before{ 
    content: ""; 
    display: block; 
    padding-top: 100%; 
} 

容器內部是一個圖像的持有人,並在此圖像。圖像必須受到限制,其高度或寬度不得超過容器並仍保持寬高比。這是通過:

img{ 
    position: absolute; 
    top: 0; 
    left: 0; 
    bottom: 0; 
    right: 0; 

    max-height: 100%; 
    max-width: 100%; 
    width: auto; 
    height: auto; 

} 

我的問題是關於圖像持有人,我需要這是相同的寬度和高度,因爲這是它內部的圖像。我怎樣才能做到這一點?請僅使用CSS。

+0

http://jsfiddle.net/1tbrtoaj/2/? – 2015-03-31 14:59:02

+0

@ Mr.Alien容器div的高度不再等於寬度 – panthro 2015-03-31 15:01:23

+0

@panthro你解決了嗎? – JohnnyQ 2016-07-19 10:39:18

回答

-1

https://jsfiddle.net/1tbrtoaj/4/

刪除位置:從你的img標籤絕對的。

.container{ 
    background-color: #e6e6e6; 
    position: relative; 
} 

.container:before{ 
    content: ""; 
    display: block; 
    padding-top: 100%; 
} 

.img-holder { 
    border-style: solid; 
    border-color: #0000ff; 
} 

img{ 
    top: 0; 
    left: 0; 
    bottom: 0; 
    right: 0; 

    max-height: 100%; 
    max-width: 100%; 
    width: auto; 
    height: auto; 
} 
+0

圖像現在是一半的容器和容器的高度現在不一樣,因爲它的寬度 – panthro 2015-03-31 15:20:27

+0

在容器中的定位可以通過刪除填充頂部:100%從.container: – TonalLynx 2015-03-31 15:29:13

+0

是的,但是 - 容器的高度現在不是相同的寬度 – panthro 2015-03-31 15:34:46

相關問題