Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 206
Jacka Avatar asked Jul 01 '16 16:07

Jacka


People also ask

Can I set width of span?

The <span> tag is a inline element, it fits into the flow of the content and can be distributed over multiple lines. We can not specify a height or width or surround it with a margin.

How do I change the content width in CSS?

Using inline-block property: Use display: inline-block property to set a div size according to its content.

What does width 100% do in CSS?

It seems like this should be one of the easiest things to understand in CSS. If you want a block-level element to fill any remaining space inside of its parent, then it's simple — just add width: 100% in your CSS declaration for that element, and your problem is solved.


2 Answers

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>
like image 164
Icycool Avatar answered Oct 06 '22 14:10

Icycool


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");
like image 28
labago Avatar answered Oct 06 '22 12:10

labago