2016-08-24 120 views
0

我有一個HTML代碼,這樣的寬度:如何設置一個div等於其兄弟IMG的寬度

<div class="card"> 
    <div class="card-content"> 
     <img src="somesource.png" width=480px height=320px> 
     <footer> 
     Some text here that makes the width of this footer greater than the width of sibling img tag. 
     </footer> 
    </div> 
</div> 

我想頁腳具有相同的寬度作爲其兄弟的IMG沒有影響圖像的寬度。圖像的寬度將根據所包含的圖像而有所不同,但我希望頁腳的寬度與圖像的寬度完全相同。 我曾嘗試以下:

.card { 
    display: inline-block; 
} 
.card-content { 
    display: flex; 
    flex-direction: column; 
} 

但它拓寬了IMG如果頁腳比圖像更廣泛。這不是我想要的。我希望頁腳的寬度取決於圖像的寬度,而不是相反。

請幫幫我。提前感謝您的建議。

回答

0

試試這個

$(document).ready(function(){ 
 

 
    var x = $(".card-content > img").width(); 
 
    var y = $(".card-content > footer").width(); 
 
    y = x; 
 
    if(y == x) { 
 
     $(".card-content > footer").css("width", x); 
 
     } 
 
    else{ 
 
     alert("na"); 
 
    } 
 
    
 
});
.card { 
 
    display: inline-block; 
 
} 
 
.card-content { 
 
    display: flex; 
 
    flex-direction: column; 
 
    
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> 
 

 
<div class="card"> 
 
    <div class="card-content"> 
 
     <img src="http://searchengineland.com/figz/wp-content/seloads/2015/10/google-panda-name3-ss-1920-800x450.jpg" width=480px height=320px> 
 
     <footer> 
 
     Some text here that makes the width of this footer greater than the width of sibling img tag. 
 
     </footer> 
 
    </div> 
 
</div>

+0

非常感謝。它工作得很好。 –

1

爲此,您可以在父元素上使用display: table並設置width: 1%

.card-content { 
 
    display: table; 
 
    width: 1%; 
 
} 
 
footer { 
 
    background: lightgreen; 
 
}
<div class="card"> 
 
    <div class="card-content"> 
 
    <img src="http://placehold.it/480x320"> 
 
    <footer> 
 
     Some text here that makes the width of this footer greater than the width of sibling img tag. 
 
    </footer> 
 
    </div> 
 
</div>

+0

我很好奇,如果這個可以用'flexbox'也可以做? – kukkuz

+0

@kukkuz我不確定。 –

1

添加max-width。希望它也足夠在相同的寬度

.card-content { 
    display: flex; 
    flex-direction: column; 
max-width:480px; 
} 
2

由於兩個圖像和頁腳是在沒有其他兄弟姐妹一樣div來查看元素,它們可以輕鬆地與類卡片內容父DIV的寬度相同。

只需添加

img{ 
width : inherit; 
} 

footer : { 
width : inherit 
} 

小提琴:https://jsfiddle.net/qo6e9882/1/