Chris Chris - 1 month ago 5
CSS Question

setting width of container based on line length

I need to set a poem that has some left-, right- and fully-justified lines. Is there a way to set the width of the container to match a particular (the longest) line rather than guessing?

Here's a mockup demonstrating the layout in Word (note the line that says "this is the line by which the section is measured" which determines the size of the box within which the text appears).

enter image description here

How can I achieve this layout with CSS?

Answer

You can nest paragraphs inside a <div> to get effect you're looking for. The outer, containing <div> should use display: inline-block to have its width set by its children.

In the example snippet, the middle line is editable. You can add or remove characters to see the container stretch and shrink to match:

.container {
  border: solid;
  display: inline-block;
}
.right-aligned {
  text-align: right;
}
<div class="container">
  <p>left aligned</p>
  <p contenteditable="true">a full width line that sets the width of the container</p>
  <p class="right-aligned">right aligned</p>
</div>

In order to get a justified line to stretch the full width of the box, you have to implement some pseudo-element trickery, there's another answer here with the solution.

In your case you add an :after pseudo-element to your justified class and style it in a way that it creates a new line within your paragraph. This should force the line of text to behave like a paragraph and justify both left and right sides.

To get rid of the blank line you can just set a height on the justified paragraph:

.container {
  border: solid;
  display: inline-block;
}
p {
  border: 1px dotted red;
}
.right-aligned {
  text-align: right;
}
.justified {
  text-align: justify;
}
.justified:after {
  content: "";
  display: inline-block;
  width: 100%;
}
.no-space {
  height: 1.2em;
}
<div class="container">
  <p>left aligned</p>
  <p contenteditable="true">a full width line that sets the width of the container</p>
  <p class="right-aligned">right aligned</p>
  <p class="justified">justified text with blank line</p>
  <p class="justified no-space">justified text without the following blank line</p>
</div>

Comments