How to change font size depending on width of container?

How to change Font Size Depending on Width of Container?

Crafting a website that provides an optimal viewing experience across different devices can be a daunting and daring task. With a multitude of screen sizes and resolutions to take into notice, ensuring that your website is easily graspable and still be visually appealing on every device can be an uphill battle. Nevertheless, one important aspect of responsive web design that can aid in this is ammending the font size based on the width of the container. You can achieve this by using CSS units like «viewport width» (vw), «media queries» or jQuery plugins like FitText to produce text elements that automatically adapt their font size to fit the available space.In this article, we shall explore the nuances of adapting font size in accordance with container width, and how implementing this methodology can elevate the user experience and enhance accessibility across a diverse range of devices.

Container

In the modern world of web design, a container is just what its name might suggest i.e. an HTML element that wraps and contains other elements, offering both a structural and stylistic framework for them. Containers play a noteworthy role in characterising the general layout of a web page, as they permit you to have full control while grouping and positioning elements relative to one another. They can be applied in various ways, such as a element that houses the primary sections of a page, like the header, main content, and footer, and grants them a shared background color and padding. Additionally, containers can be nested within one another, allowing for more intricate and dynamic designs. Through the manipulation of the size, position, and functionality of containers, a diverse range of web layouts can be achieved.

Читайте также:  Javascript createobject adodb connection

Approach

We are going to take a look at a diverse range of ways to change the font size, extending from CSS viewport and media queries to jQuery plugins. The methods we are going to take a look at in this article are as follows −

Method 1: Using Viewport Width

The CSS «viewport width» property, additionally also referred to as «vw», is a percentage-based unit of measurement that amount to the width of the visible area of a webpage. It enables designers to specify the width of an element as a percentage of the viewport width by using the «vw» unit of measurement in CSS. This approach is on the whole is extremely beneficial for creating responsive designs that can accommodate various screen sizes and devices. Utilizing vw units enables designers to maintain the element’s proportions relative to the viewport width, ensuring that the design looks visually appealing on all devices.

The HTML code provided below contains a simple example of how to change the font size of text inside a container based on the width of that container. This code contains two parts −

The body contains a container div tag. This container has a class named «container,» and it contains the text enclosed in a paragraph tag. The CSS code inside the head element targets this container’s paragraph element and sets its font size to be 5% of the viewport width, or vw. In this manner, the font size will calibrate to the width of the container as the container’s size switches.

Example

The following is the complete code that we are going to use in this example −

    .container p 

How to change font size depending on width of container?

This is some text.
This is some more text.
This is some more more text.

Method 2: Using Media Queries

To achieve responsive designs that function well on various devices, Media Queries is a valuable tool used by designers and developers in CSS. This technique makes it possible to apply different styles to a web page based on the characteristics of the device or display it is being viewed on. Media queries evaluate conditions like screen size, resolution, and orientation, and subsequently apply CSS styles based on those conditions. This capability allows the creation of dynamic and flexible designs that can adapt to the unique properties of each device, from small smartphones to large desktop screens. A media query is implemented using the @media rule and includes a media type and one or more expressions that check for particular conditions. When those conditions are satisfied, the styles defined within the media query are applied. As a result, Media Queries offers an influential solution for crafting responsive designs that cater to the abilities and limitations of different devices.

The body element contains the dummy elements whose font sizes we are going to affect while the CSS stylesheet lays the rules for changing the sizes.

Delving deep into the nitty-gritty of the code you will realise that the initial font size is set to 24 pixels. However, there are three media queries defined for three different screen sizes. The first one is concerned with screens that have a maximum width of 767 pixels. In this media query, we set the font size to be 18 pixels. The next media query is for displays with a minimum width of 768 pixels and a maximum width of 1023 pixels. In this media query, we update the font size to be 20 pixels. The final media query is concerned with displays with a minimum width of 1024 pixels. In this media query we reset the font size to the initial size of 24 pixels. The paragraph to which the font size is applied is wrapped in a div with a class of «container». When the page is loaded, the default font size of 24 pixels will be applied to the paragraph which will by the use of media queries will get updates as and when the display size changes.

Example

The following is the complete code which we are going to use in this example −

      

How to change font size depending on width of container?

This is some text.
This is some more text.
This is some more more text.

Method 3: Using FitText jQuery Plugin

FitText is a jQuery plugin or library that provides functionalities that automatically resizes and balances the font size of an element to fit the width of its container. This plugin works by handling and fine tuning the font-size property of an element, based on the current width of the parent container element. This allows web developers with the opportunity for creating dynamic and responsive typography that adjusts to different screen sizes and devices.

This HTML code loads a JavaScript library called FitText that allows for responsive font scaling based on the width of the container element. We have used CDN as you can see in the head element to load the FitText library. The code also includes a container element with some text paragraphs inside, and a script that uses jQuery to initialize the FitText plugin on the paragraph elements within the container. The FitText plugin axiomatically balances the font size of the text to fit the available width of the container, ensuring that the text is always readable and visually appealing on different devices with varying screen sizes.

Example

The following is the complete code which we are going to make use of in this example −

      

How to change font size depending on width of container?

This is some text.
This is some more text.
This is some more more text.

Conclusion

In summary, modifying the size of the font based on the size of the container is a valuable method for building designs that can adapt to diverse screen sizes and devices. The CSS «viewport width» (vw) unit offers a versatile and natural way to specify the font size by depending on the viewport width. By combining media queries and either vw units or FitText plugin, you can specify distinct font sizes for different breakpoints and make sure that the text elements appear appealing and readable on any gadget. No matter if you’re working on a primitive landing page or an aggregated web application, employing this approach will help you put up a better user experience and enhance the overall appearance and impression of your designs.

Источник

Viewport Sized Typography

There are values in CSS that are for sizing things in relation to the viewport (the size of the browser window). They are called viewport units, and there are a number of them that do slightly different (all useful) things. One unit is 1% of one of the axes of the viewport. These can be useful for responsive design, that is, designing websites that look good across different screen sizes, taking advantage of the space available to them. There are many things you can do with viewport units, but let’s look at one in particular: typography. It’s worth looking at our more recent post Simplified Fluid Typography for practical, clamped, viewport-based type sizing.

  1. There is a such thing as a comfortable line length for reading text on screens. I don’t want to kick a hornet’s nest, but let’s say its around 80 characters. These units allow you to get it feeling perfect and then have that experience scale to any size screen.
  2. They allow you to tightly couple the size relationship of, say, a typographic header and the content it goes with. Like your classic Trent Walton style blog post.

One unit on any of the three values is 1% of the viewport axis. “Viewport” == browser window size == window object. If the viewport is 40cm wide, 1vw == 0.4cm.

For use with font-size , I guess it’s one “letter” that takes on that size, but as we know, in non-mono-spaced fonts the width of a letter is rather arbitrary. I find you just need to tweak around with the values to get it how you want it. Which is basically what we do anyway, right?

  • 1vw = 1% of viewport width
  • 1vh = 1% of viewport height
  • 1vmin = 1vw or 1vh , whichever is smaller
  • 1vmax = 1vw or 1vh , whichever is larger

Here’s a video of a simple layout using vw units for the font-size .

Check out the demo yourself (see browser support).

Or here’s a GIF for a super simple header:

The support is there in Chrome 20+ / Safari 6+, but it fails in one rather significant way. When the browser window is resized, the font doesn’t adjust itself according to the new viewport size. The spec says:

When the height or width of the viewport is changed, they are scaled accordingly.

I bugged it. Perhaps not a huge disaster as it’s pretty much just us design nerds that go around adjusting browser windows, but still. The font does adjust on a fresh page load.

To fix this issue (allow resizing without page refresh) you need to cause a “repaint” on the element. I used jQuery and just fiddled with each elements (irrelevant, in this case) z-index value, which triggers the repaint.

causeRepaintsOn = $("h1, h2, h3, p"); $(window).resize(function() < causeRepaintsOn.css("z-index", 1); >);

UPDATE: Don’t worry about this anymore and definitely don’t be forcing those repaints. This resizing issue is fixed in Chrome 34+ and Safari 7+. It’s not common to change the viewport size on mobile devices, so I’m not sure if this bug ever affected them or not.

IE 10+, Firefox 19+, Chrome 34+, Safari 7+, Android 4.4+, iOS 6+Supported

Chrome 20-34, Safari 6Supported but has repaint issue

There are a couple of other specific cross-browser weirdnesses with them, documented on Can I Use.

For the record, these are just units. Just like em , px , whatever. You can use them on anything, not just font-size .

I think font-size is the most compelling use case, since things like margin, padding, and width can already essentially react to browser window size by using % units. There is the case where perhaps a more deeply-nested element needs to react to the browser window size instead of its direct parent size.

You’ll at least want to provide a fallback:

Modernizr doesn’t have a test for it yet, but you can test for it yourself by using some throw-away element that you see to some narrow width in CSS but then re-set to 100vw in JavaScript, then measure to see if the width of it is equal to window.width. Something like:

var testEl = $("#vw-test"); testEl.css(< width: "100vw" >); if (testEl.width() == window.innerWidth) < // Supported >else < // Not Supported >;

Here’s that test on CodePen, but note it only works in Full Page view otherwise the calculation might be off because of iframe issues.

Mimic the functionality with FitText.js

This idea of binding the overall width of a header with the width of its parent element is exactly what FitText.js does. Only it does it through fancy JavaScript and math and spans and stuff. Theoretically, you could run the test and use Modernizr.load to load up FitText.js if no support is detected.

Источник

Оцените статью