Document

Resize the width of a text box to fit its content automatically

Let’s say that an input has the id of textbox as below:

To adjust its width based on its content dynamically, we create a fake element whose content is the same as the input value. And we set the input’s width as the fake element’s width.

// Create a div element
const fakeEle = document.createElement('div');

// Hide it completely
fakeEle.style.position = 'absolute';
fakeEle.style.top = '0';
fakeEle.style.left = '-9999px';
fakeEle.style.overflow = 'hidden';
fakeEle.style.visibility = 'hidden';
fakeEle.style.whiteSpace = 'nowrap';
fakeEle.style.height = '0';

// We copy some styles from the textbox that effect the width
const textboxEle = document.getElementById('textbox');

// Get the styles
const styles = window.getComputedStyle(textboxEle);

// Copy font styles from the textbox
fakeEle.style.fontFamily = styles.fontFamily;
fakeEle.style.fontSize = styles.fontSize;
fakeEle.style.fontStyle = styles.fontStyle;
fakeEle.style.fontWeight = styles.fontWeight;
fakeEle.style.letterSpacing = styles.letterSpacing;
fakeEle.style.textTransform = styles.textTransform;

fakeEle.style.borderLeftWidth = styles.borderLeftWidth;
fakeEle.style.borderRightWidth = styles.borderRightWidth;
fakeEle.style.paddingLeft = styles.paddingLeft;
fakeEle.style.paddingRight = styles.paddingRight;

// Append the fake element to `body`
document.body.appendChild(fakeEle);

The function below sets the HTML for the fake element, calculates its width and sets the result to the original input.

const setWidth = function ()  
const string = textboxEle.value || textboxEle.getAttribute('placeholder') || '';
fakeEle.innerHTML = string.replace(/\s/g, '&' + 'nbsp;');

const fakeEleStyles = window.getComputedStyle(fakeEle);
textboxEle.style.width = fakeEleStyles.width;
>;

This post introduces more ways to measure the width of given text in given font

Finally, we invoke the setWidth function when users change the input value by listening on the input event:

setWidth();

textboxEle.addEventListener('input', function (e)
setWidth();
>);

Источник

Fitting Text to a Container

There are a number of ways to go about putting some text in a container and having it size itself to fill that container. There are different technologies we can use and different considerations to think about. Let us count the ways.

Magic Number it with viewport units

If you set type with vw (viewport width) units, you can find an exact number where the text pretty closely fits the container and doesn’t break as you resize. I’d call this a magic number. In this case, font-size: 25.5vw; works down to a 320px viewport, but still will break much lower than that. See the Pen Fitted Text with Viewport Units by Chris Coyier (@chriscoyier) on CodePen. This is kind of a less exotic version of fluid typography, which involves more of a sprinkling of viewport units and min/max sizes.

Dave Rupert’s FitText is up for the job. You still need a bit of a magic number to get the sizing just right for any particular job: See the Pen Fitted Text with FitText by Chris Coyier (@chriscoyier) on CodePen.

Swap the words in FitText around and you got yourself textFit! It’s another JavaScript library that adjusts font sizes to fit text into a container. Big caveat here though: textFit is designed for two-dimensions. So you need a width and height on the element for it to do it’s thing.

fitty is more like FitText in that it resizes type to maximize just horizontally, but actually seems to require no magic numbers.

TextFill is jQuery-based and requires a width, height, and a configured maximum font size to work. Here’s the basic demo we’ve been working from:

FlowType is kind of designed to work on a whole document of text, resizing it all fluidly at once, with minimum and maxium viewport sizes. But you can scope it however you want. You also apply a magic number to get things how you want them.

With width: 100% and a viewBox , SVG will be a fullsize box that resizes with an aspect ratio. Pretty neat trick! To set the type, you’ll need some magic numbers to get that viewBox just right and push the text into the right spot — but it’s doable with zero dependencies, just like the viewport units demo.

Psst! Create a DigitalOcean account and get $200 in free credit for cloud-based hosting and services.

Comments

PSA: vw is broken, because it measures what is every single time the wrong thing. It measures the viewport’s initial containing block, which means the entire viewport width including the vertical scrollbar that is almost certain to be there. This matters on operating systems that don’t use overlay scrollbars (Windows, many Linuxes, and some macOS users opt out of overlay scrollbars); on Windows, it’ll generally amount to 100vw actually being 17px wider than the body width. Therefore I say, if you are trying to measure things precisely with vw: (a) just don’t, you can’t succeed; and (b) if you insist on it anyway, make sure to allow at least 20px of slack (if that’s not acceptable, vw will not solve your problem)—and be ready to accept that even then your calc(100vw – 20px) may be wider than the body width in some circumstances.

Good to know. I find when I’m using viewport units I’m often not looking for super precision. I often use them to sprinking in a little viewport related bumps up and down with calc.

The best way I’ve gone about solving this is creating a CSS variable —window-width and set it to 100vw . Then in javascript i set this CSS variable to document.body.clientWidth which will get the width of window without the scrollbar.

Any suggestions on how to fit text vertically? I always end up with space above and below that I can’t seem to get rid of without adjusting line-height with magic numbers

Only the SVG worked properly in Firefox, none of the others. Neither textFit or TextFill work in Chrome or Firefox. fitty seemed to only react after screen resize event “ended”, but not live. (by design?) All of these feel like the incredibly awful Flash based text of 10 years ago, except for pure CSS using vw (why call this a “magic” number when it’s simple math/calc going on… nothing magic, and makes total sense) The Flash criticism is a bit funny to me because it really was just a clumsy SVG, but SVG is just an “image”, which I can get behind for custom uses. I agree that trying to make any adjustments with text “exact” is a recipe for disaster and reminds me of print designers making entire page layouts, with text, all as one image because they hated how they couldn’t control the design perfectly. Let go of control, and either style with breakpoints, vw + calc (or whatever) and let go of perfection. You get better designs and less stress. If you need pixel prefect layout, SVG to the rescue. CSS shouldn’t have to fill every niche need, it’s pulling more than it’s weight already.

Источник

Css how to make text fit inside div

Now just so your text does not leave the container div #overlay_image_text added to the word-wrap You can see more in https://developer.mozilla.org/es/docs/Web/CSS/word-wrap http://www.w3schools.com/cssref/css3_pr_word-wrap.asp Solution: What I would do to fix your problem is change the CSS file to this and check the result on different screen sizes: Give an height that later can be changed when you add more elements in your HTML file Give a width and a height to encapsulate the headers and prevent overflow Give a to prevent it from taking extra unwanted space Hope this will fix your problem!Solution: You need a few things to make this happen without extra markup. Solution 1: Here’s the same answer, but in Javascript By the way. if you ever need to convert coffeescript to javascript, just go to js2coffee.org Solution 2: I was wanting something similar myself recently: And Fiddler at jsfiddle.net/mn4rr/1/. Solution 3: I don’t have enough reputation to comment on the accepted answer so I made an answer.

How to fit text inside a HTML div

You need a few things to make this happen without extra markup.

.left-rounded-corner < . line-height: 16px; box-sizing: border-box; /* include padding and margin in height */ padding-top: 10px; /* move text down a bit */ >.textStyle < . font-size: 90%; /* something big enough to force wrap without extra markup */ white-space: normal; /* allow wrapping */ >

Fit-content() — CSS: Cascading Style Sheets, 6 days ago · The function can be used as a track size in CSS Grid properties, where the maximum size is defined by max-content and the minimum size by auto ,

Fit text perfectly inside a div (height and width) without affecting the size of the div

Here’s the same answer, but in Javascript

var autoSizeText; autoSizeText = function() < var el, elements, _i, _len, _results; elements = $('.resize'); console.log(elements); if (elements.length < 0) < return; >_results = []; for (_i = 0, _len = elements.length; _i < _len; _i++) < el = elements[_i]; _results.push((function(el) < var resizeText, _results1; resizeText = function() < var elNewFontSize; elNewFontSize = (parseInt($(el).css('font-size').slice(0, -2)) - 1) + 'px'; return $(el).css('font-size', elNewFontSize); >; _results1 = []; while (el.scrollHeight > el.offsetHeight) < _results1.push(resizeText()); >return _results1; >)(el)); > return _results; >; $(document).ready(function() < return autoSizeText(); >); 

By the way. if you ever need to convert coffeescript to javascript, just go to js2coffee.org

I was wanting something similar myself recently:

Fiddler at jsfiddle.net/mn4rr/1/.

I don’t have enough reputation to comment on the accepted answer so I made an answer. If height has a css3 transition on it the autoSizeText() and $.resizeText answers above have issues. I made a short jquery plugin to fix this.

$.fn.resizeText = function (options) < var settings = $.extend(< maxfont: 40, minfont: 4 >, options); var style = $('').html('.nodelays ' + '< ' + '-moz-transition: none !important; ' + '-webkit-transition: none !important;' + '-o-transition: none !important; ' + 'transition: none !important;' + '>'); function shrink(el, fontsize, minfontsize) < if (fontsize < minfontsize) return; el.style.fontSize = fontsize + 'px'; if (el.scrollHeight >el.offsetHeight) shrink(el, fontsize - 1, minfontsize); > $('head').append(style); $(this).each(function(index, el) < var element = $(el); element.addClass('nodelays'); shrink(el, settings.maxfont, settings.minfont); element.removeClass('nodelays'); >); style.remove(); > 

To use this plugin you only need to call

I hope this saves someone else some time troubleshooting. I wasted a good 20 minutes scratching my head wondering why the code above was causing an infinite loop on my page.

How to fit text inside a HTML div, You need a few things to make this happen without extra markup .left-rounded-corner < line-height: 16px; box-sizing: border-box;

How to force a text to fit inside a div

Do like this, where you measure the text size

Made a minor update where the min font size is passed as a param

function getStyle(elem,prop) < return window.getComputedStyle(elem,null).getPropertyValue(prop); >function setFontSize(elem,minsize) < var tst = document.createElement('div'); tst.textContent = elem.textContent; tst.style = 'position:absolute;left:-9999px;display:inline-block;'; document.body.appendChild(tst); tst.style.fontSize = minsize + 'px'; tst.style.fontWeight = getStyle(elem,'font-weight'); tst.style.fontFamily = getStyle(elem,'font-family').split(',')[0]; while (minsize < 1000) < if (parseInt(getStyle(tst,'width')) >200) < elem.style.fontSize = (minsize - 2) + 'px'; break; >tst.style.fontSize = minsize++ + 'px'; > document.body.removeChild(tst); >setFontSize(document.querySelector('.sizedtext'),5);

You can toggle the below class:

$(element).addClass('myFitClass'); // ^^^ -> also `removeClass` or even `toggleClass` 

You can optimize your code even more, you repeat a lot of syntax and do your code slower.

if (cs >= 1 && cs ); > else if(this.engravingFontCaseSenstiveOptions(cText) == "Upper") < $('#overlay_image_text').css(< 'margin-top' : '-154px', 'margin-top' : '-154px', 'font-size' : '48px', 'margin-left' : '0px' >); > else < $('#overlay_image_text').css(< 'margin-top' : '-162px', 'font-size' : '60px', 'margin-left' : '0px' >); > > else if(cs == 5) < if(this.engravingFontCaseSenstiveOptions(cText) == "Lower") < $('#overlay_image_text').css(< 'margin-top' : '-152px', 'font-size' : '54px', 'margin-left' : '0px' >); > else if(this.engravingFontCaseSenstiveOptions(cText) == "Upper") < $('#overlay_image_text').css(< 'margin-top' : '-143px', 'font-size' : '45px', 'margin-left' : '0px' >); > else < $('#overlay_image_text').css(< 'margin-top' : '-143px', 'font-size' : '45px', 'margin-left' : '0px' >); > > 

Now just so your text does not leave the container div #overlay_image_text added to the word-wrap

You can see more in https://developer.mozilla.org/es/docs/Web/CSS/word-wrap http://www.w3schools.com/cssref/css3_pr_word-wrap.asp

Fit text perfectly inside a div (height and width) without affecting the, Where text-wrapper is parent and aligned-text is child div. You must specify height and width of parent element. In resize you can set height and width of

How to fit an enlarged h1 within a div without the text overlapping?

What I would do to fix your problem is change the CSS file to this and check the result on different screen sizes:

  1. Give body an height that later can be changed when you add more elements in your HTML file
  2. Give main-page-font a width and a height to encapsulate the headers and prevent overflow
  3. Give main-page-font a display: inline-block; to prevent it from taking extra unwanted space
body < margin: 0; padding: 0; background-color: orangered; height: 100vh; >.main-page-font < background-image: linear-gradient(to left, blue, grey); width: fit-content; height: fit-content; display: inline-block; background-size: cover; >.headers h1, .headers h3 < color: azure; >h1
         
This is a long header for this page

Fit me within this space please

Hope this will fix your problem!

How to make text take full width of it’s container?, the vw stands for viewport width , in this example 4.3% of the width of the viewport. Play around with that to get your text fit on one line.

Источник

Читайте также:  Получить адрес https php
Оцените статью