Paymahn Moghadasian
Paymahn Moghadasian

Reputation: 10339

Bind width of one element to width of sibling

I'm trying to set the max width of a <p> tag to the width of a sibling <p> tag.

Here's the relevant code:

<div>
  <p>
    <h2 id="annotation_preview_title"> <%= t('marker.annotation.preview_title') %></h2>
  </p>
  <p id="annotation_preview" style="word-wrap: break-word;"></p>
</div>

I'm using jquery to populate the content of annotation_preview and I would like it's width to not exceed the width of the <p> tag surrounding annotation_preview_title.

Here's an image of the problem I'm trying to solve: Annotation is too long

I'd like to get the annotation_preview to wrap once it reaches the width of annotation_preview_title. I've tried using css as found here (from another SO post I closed) and tried playing with jQuery doing something to the effect of:

var previewParagraph = document.getElementById("annotation_preview");
var title = document.getElementById("annotation_preview_title");
previewParagraph.maxWidth = title.width;

Neither of which worked. I'm open to any and all solutions (pure JS, pure CSS, mix, whatever).

Upvotes: 0

Views: 1052

Answers (1)

simpleManderson
simpleManderson

Reputation: 436

Since you're already using jQuery:

$("#annotation_preview").css("max-width", $("#annotation_preview_title").width());

I haven't tested it, but something along these lines should do the trick.

Upvotes: 2

Related Questions