2016-08-24 57 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/

相关问题