Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stretch text to fit width of div

Tags:

html

css

I have a div with a fixed width, but the text inside the div can change.

Is there a way of setting, with css or other, the spacing between the letters so the text always fills the div perfectly?

like image 471
Curtis Avatar asked May 12 '11 09:05

Curtis


People also ask

How do I stretch the width of a div?

There are two methods to stretch the div to fit the container using CSS tat are discussed below: Method 1: First method is to simply assign 100% width and 100% height to the child div so that it will take all available space of the parent div. Consider this HTML for demonstration: HTML.

How do you fit a full width to a div?

What you could do is set your div to be position: absolute so your div is independent of the rest of the layout. Then say width: 100% to have it fill the screen width. Now just use margin-left: 30px (or whatever px you need) and you should be done.

How do I change the width of a div in text?

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


1 Answers

This can be done with text-align:justify and a small hack. See here:

div{    background-color:gold;    text-align:justify;  }    span{    background-color:red;    width:100%;    height:1em;    display:inline-block;  }
<div>    Lorem ipsum sit dolor    <span> </span>  </div>

The trick is to add an element after the text that pretends to be really long word. The fake word is actually a span element with display:inline-block and width:100%.

In my example the fake word is in red and given a height of 1em, but the hack will work even without it.

like image 143
Aakil Fernandes Avatar answered Oct 11 '22 00:10

Aakil Fernandes