当一个 div 的宽度为 width: auto;
时,是否可以将该 div 的宽度设置为与它最近的兄弟相同?
在my jsFiddle你会看到我有一个红色、绿色和蓝色的 div。我希望蓝色 div 调整为绿色 div(动态)的大小。因此,如果绿色 div 为 200px,那么我希望蓝色 div 为 200px。
最初我以为我可以将蓝色 div 放在绿色 div 中并在 child 上设置 display: inline-block
,但这不起作用。
因此,如果蓝色 div 的内容增加,那么它不会将绿色 div(或容器 div)的宽度推出。如何实现?
最佳答案
如果您愿意使用 JavaScript,您可以在要跟踪的 div 发生变化时调整宽度。使用 jQuery,很简单:
$(document).ready(function() {
// Function to sync the sizes of the divs
function syncSize() {
$("#banner_description").width($(".banner_secondary_title").outerWidth(true));
}
// Sync the size when a change is made
$(".banner_secondary_title").resize(function(e) {
syncSize();
});
// Initial sync after document setup
syncSize();
});
这是你的 jsFiddle 的 fork 添加此代码后,我还向次要标题添加了更多文本以展开它以表明它有效。
关于javascript - 将 div 的宽度设置为与其最近的兄弟相同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12605969/