简体   繁体   中英

Set width of a span based on width of another element with pure css

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

.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.

Codepen: 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.

It's a little bit gimmick but it can be done with pure 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>

I don't really think you can accomplish this with CSS. Try a jquery solution like this:

var $setter = $("#setter");
$setter.siblings(".wrap").css("max-width", $setter.width()+"px");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM