Javascript 使用纯css根据另一个元素的宽度设置跨度的宽度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38150525/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Set width of a span based on width of another element with pure css
提问by Hymana
HTML
HTML
<div class="container">
<div id="setter">
<span>some variable content</span>
</div>
<div class="wrap">
<span>
lorem ipsum lorem ipsum lorem ipsum lorem ipsum
</span>
</div>
</div>
CSS
CSS
.container {
max-width: 200px;
}
.wrap {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
The case:
案子:
I need to set the width of a span inside .wrap
class based on the width of a span inside #setter
div dynamically. As you can see in css I'm using ellipsis
overflow on the second div. The setter
div content length is going to vary. So the goal is to make the lorem ipsum
text be not wider than the content of the first div.
我需要.wrap
根据#setter
div内部跨度的宽度动态设置类内部跨度的宽度。正如您在 css 中看到的,我ellipsis
在第二个 div 上使用了溢出。该setter
DIV内容长度将会有所不同。所以目标是使lorem ipsum
文本不比第一个 div 的内容宽。
Codepen: http://codepen.io/jacek213/pen/pbPkmQ
代码笔:http://codepen.io/jacek213/pen/pbPkmQ
I want to achieve this with pure css, is that possible? If not, an angular-friendly solution in js (jquery usage is ok) is welcome, however I need it to be efficient because I'm going to display a large number of records built with this structure at once.
我想用纯 css 来实现这一点,这可能吗?如果没有,欢迎使用 js 中的角度友好的解决方案(jquery 可以使用),但是我需要它是高效的,因为我将一次显示大量使用此结构构建的记录。
回答by Icycool
It's a little bit gimmick but it can be done with pure CSS
这有点噱头,但可以用纯 CSS 来完成
#setter {
display: inline-block;
}
.container {
max-width: 200px;
position: relative;
display: inline-block;
padding-bottom: 1.125em;
}
.wrap {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
position: absolute;
left: 0;
right: 0;
}
<div class="container">
<div id="setter">
<span>some variable content</span>
</div>
<div class="wrap">
<span>
lorem ipsum lorem ipsum lorem ipsum lorem ipsum
</span>
</div>
</div>
回答by labago
I don't really think you can accomplish this with CSS. Try a jquery solution like this:
我真的不认为你可以用 CSS 来完成这个。尝试这样的 jquery 解决方案:
var $setter = $("#setter");
$setter.siblings(".wrap").css("max-width", $setter.width()+"px");