Test input text in table

width

Свойство width отвечает за ширину элемента. С его помощью мы можем увеличивать или уменьшать ширину строчно-блочных ( inline — block ) и блочных ( block ) элементов. На строчные элементы это свойство не будет иметь никакого влияния.

Строчно-блочные ( inline — block ) элементы по умолчанию подстраиваются под ширину контента, лежащего у них внутри.

Блочные ( block ) элементы по умолчанию имеют ширину 100%. Если представить сайт как документ с текстом, то блочный элемент займёт всю строку, на которой стоит.

Кроме фиксированной ширины можно задавать элементу минимальную ширину min — width или максимальную ширину max — width .

В современном CSS есть логический аналог этого свойства — inline — size .

Пример

Скопировать ссылку «Пример» Скопировано

 
Я — блочный элемент!
Я
строчно-блочный
элемент!
div class="block">Я — блочный элемент!div> div class="inline-block">Яdiv> div class="inline-block">строчно-блочныйdiv> div class="inline-block">элемент!div>

Не меняем display для .block , поскольку уже является блочным:

 .block  background-color: #2E9AFF;> .inline-block  display: inline-block; background-color: #F498AD;> .block  background-color: #2E9AFF; > .inline-block  display: inline-block; background-color: #F498AD; >      

Пример макета

Теперь любой текст будет занимать не больше, чем 50% от ширины карточки 🎉

Источник

Stretch text to fit width of div

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?

Do you want to change the «spacing between the letters» (as in letter-spacing ) or the font-size ? Edit: or as in @SmudgerDan’s answer, the spacing between the words?

@GeorgeKatsanos I find «text-align:justify» doesn’t always fill the area correctly. For example, if I have a div with 300px width, with the text content «Lorem Ipsum», this doesn’t stretch to fill the area

13 Answers 13

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

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.

This works great if we want to split the words evenly, but I wish to separate the letters evenly. Is there any way of adjusting this script to do just that?

Not sure what you mean by «separated the letters evenly». Do you mean that each letter should be separated uniformly, regardless of spaces?

He means that this is a solution to a question that is different from the one that he asked. What he is asking is how a single word can be spaced to fill a container, not multiple words. Letter spacing vs word spacing. Of course, the solution should work for words as well — but by spacing every letter, not every word. If there is just a single word, your solution does nothing.

As Mark said, text-align:justify; is the simplest solution. However, for short text, it won’t have any effect. The following jQuery code stretches the text to the width of the container.

It calculates the space for each character and sets letter-spacing accordingly so the text streches to the width of the container.

If the text is too long to fit in the container, it lets it expand to the next lines and sets text-align:justify; to the text.

Here is a demo :

$.fn.strech_text = function()< var elmt = $(this), cont_width = elmt.width(), txt = elmt.html(), one_line = $('' + txt + ''), nb_char = elmt.text().length, spacing = cont_width/nb_char, txt_width; elmt.html(one_line); txt_width = one_line.width(); if (txt_width < cont_width)< var char_width = txt_width/nb_char, ltr_spacing = spacing - char_width + (spacing - char_width)/nb_char ; one_line.css(); > else < one_line.contents().unwrap(); elmt.addClass('justify'); >>; $(document).ready(function () < $('.stretch').each(function()< $(this).strech_text(); >); >);
p < width:300px; padding: 10px 0;background:gold;>a .stretch_it < white-space: nowrap; >.justify < text-align:justify; >.one .two .three .four .arial

 

Stretch me

Stretch me

Stretch link

I am too slong, an I would look ugly if I was displayed on one line so let me expand to several lines and justify me.

Stretch me

Stretch me

Stretch me

Don't stretch me

This was very useful to me, I made a couple of changes so that it would work responsively too: jsfiddle.net/DPRr9/347

Even easier HTML/CSS method would be to use flexbox. It’s also immediately responsive. But worth noting SEO won’t pick it up if you were to use it as a h1 or something.

a little easier with flex layout.. use on wrapper div fxLayout=»row» fxLayoutAlign=»space-evenly center»

very good idea for know in advanced text and with little javascript it can also work with dynamic text.

I found a better solution for text shorter than one line, without any extra js or tag, only one class.

A little late to the party, but for a simple, pure CSS implementation consider using flexbox :

Not sure if wrapping each letter in a span (note any element will work) will mess with SEO, but I imagine search engines will strip tags from the innerHTML of tags used for important markup such as headings, etc. (Someone who knows SEO to confirm?)

Some of the above answers work well but the text has to wrap with many child div
and it’s a lot of extra codes.
The text inside the div should be clean, so I made it with a help of JS.

 const words = document.querySelector(".words"); words.innerHTML = words.innerText.split("").map(e => !e.trim() ? "
 
" : `
$ `).join("");

MARCH 2018 If you are landing on this question in a more current time.

I was attempting do do what the OP asked about but with a single word and found success with the following:

1. Use a and set css: span < letter-spacing: 0px; display:block>(this makes the element only as wide as the content)

2. On load capture the width of the span let width = $(‘span’).width();

3. Capture the length of the span let length = $(‘span’).length;

4. Reset the width of the span to the container $(‘span’).css();

5. Capture the NEW width of the span (or just use the container width) let con = $(‘span’).width();

6. Calculate and set the letter spacing to fill the container $(‘span’).css()

Obviously this can be converted to use vanilla js and it is useful even with most font styles including non mono-space fonts.

I think what you’re actually looking for is scaling.

Render your font with some nice-looking resolution that makes sense and then use JS to stretch it to the container by using css transforms:

The benefits of this is that your text will always wit, but you run into the problem of it becoming too small to be readable.

Quick note is that you’ll need to make the element you’re trying to shrink/expand have absolute position:

Except this messes with either the font size or the aspect ratio of the font itself which is not what is desired.

So, still nibbling away at the edges of this problem, if you combine wener’s answer that stretches short lines of text with this suggestion to use a real element from another thread, you can do the whole thing without needing an :after pseudo class.

You’re substituting in an actual element and placing it after the one you want to justify. And this will trigger the justify alignment in the same way:

 
A line of text to justify

This variation lets you use this trick with React and style objects:

const style = < backgroundColor: '#ace', textAlign: 'justify' >; const hack = < display: 'inline-block', width: '100%' >; const example = ( 
>
A line of words to stretch
/>
); ReactDOM.render(example, document.getElementById('root'));

This is ugly and hacky enough already, but from there you’ll have to pick your poison on which way you want to «fix» the excess height of the container: fixed height or negative margins for the container? relative positioning and overlapping from following elements? match the container background to the page background and pretend like that extra margin is intentional?

@VisionHive it’s not supposed to. it’s only solving for word justifying with css, and without pseudo-elements so that you can use css objects. see this more current answer for something like a more complete solution.

If someone is interested on how to justify the content and center only the last line you can use

text-align: justify; text-align-last: center; 
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis mollis elementum bibendum. Cras pellentesque sed augue nec lacinia. Duis at eros vel lorem cursus laoreet ac vel justo. Maecenas ornare, ligula ut porttitor sollicitudin, turpis urna auctor ipsum, a consectetur felis nibh vel est. Nullam id lorem sit amet magna mollis iaculis eu vitae mauris. Morbi tempor ut eros ut vulputate. Quisque eget odio velit. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Sed posuere enim tellus, ut vestibulum libero dapibus ac. Nulla bibendum sapien non luctus vehicula. Aenean feugiat neque nunc, in fermentum augue posuere vel. Maecenas vitae diam in diam aliquet aliquam.

Источник

HTML input textbox with a width of 100% overflows table cells

Does anyone know why the input elements with a width of 100% go over the table’s cells border. In the simple example below input box go over the table’s cells border, the result is horrible. This was tested and it happens in the same way on: Firefox, IE7 and Safari. Does it make sense for you? Am I missing something, do you know about a possible solution?

         

column one hello babe babe babe

column two hello babe more

column three hello babe more and more

I would suggest that, if you’re just using a table for presenting the inputs, you might switch to using a form with the label s and input s inside a ul or ol . which is, at least slightly more semantic. Certainly though, you should be using a form , even if you do stick with the table .

14 Answers 14

You could use the CSS3 box-sizing property to include the external padding and border:

Sad to say but unfortuately IE 7 does not deal with box sizing correctly. Try the following in IE 7. css3.info/preview/box-sizing or see css-tricks.com/box-sizing

@AnthonyVO: true, the only workaround for IE7 is to add specific CSS for it using IE conditional comments

Читайте также:  Union find algorithm python
Оцените статью