How do I ensure that my font size completely fills the space in a justified layout using CSS?

Is there a way to style my text to match the appearance in the image shown using CSS?

Answer №1

To start off, it is important to choose a mono-space font for your text. There are several attractive options available at Google Fonts, like the one used in the image, Ubuntu Mono.

Next, we will utilize Viewport Width, or 'vw' unit (check the link for browser support). Ensure the top line of text fits the desired width, and each line should be its own element as shown in this sample HTML:

<p style="font-size: 5vw;">How can I</p>
<p>Adjust my font size</p>
<p>to fill all the space</p>
<p>in a justified</p>
<p>layout?</p>

Now, we can determine the 'vw' size for the remaining lines with this formula:

NewFontSize = BaseFontSize - (((NewLineNumberOfChars - BaseLineNumberOfChars) / NewLineNumberOfChars) * BaseFontSize)

For a programmatically achieved example using JavaScript, refer to this demonstration. The resulting code is:

<p style="font-size: 5vw;">How can I</p>
<p style="font-size: 2.36842vw;">Adjust my font size</p>
<p style="font-size: 2.14286vw;">to fill all the space</p>
<p style="font-size: 3.21429vw;">in a justified</p>
<p style="font-size: 6.42857vw;">layout?</p>

Keep in mind that Google Chrome rounds font sizes to the closest pixel, which may cause slight discrepancies, especially at smaller sizes.

Answer №2

Here is an alternative approach using JavaScript without jQuery:

let baseFontSize = '';
let baseFontChars = '';
const paragraphs = document.querySelectorAll('p');
paragraphs.forEach((paragraph, index) => {
  if (index === 0) {
    baseFontSize = 3;
    const string = paragraph.innerHTML;
    baseFontChars = Array.from(string).length;
  } else {
    const string = paragraph.innerHTML;
    const newFontChars = Array.from(string).length;
    const newFontSize = baseFontSize - ((newFontChars - baseFontChars) / newFontChars) * baseFontSize;
    paragraph.style.fontSize = `${newFontSize}vw`;
  }
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Discover the ultimate strategy to achieve optimal performance with the wheel

How can I dynamically obtain the changing top position when a user moves their mouse over an element? I want to perform some checks whenever the user scrolls up, so I tried this code: HostListener('window:wheel', ['$event']) onWindowS ...

Using getServerSideProps in Next.js is preventing the global css from loading

In my Next.js application, I have defined global styles in the file /styles/globals.css and imported them in _app.tsx. // import default style import "../styles/globals.css"; function MyApp({ Component, pageProps }) { return <Component {...pageProps ...

Adjusting the opacity of the background image in the section - focus solely on the background

This section is what I'm working on. <section ID="Cover"> <div id="searchEngine">hello</div> </section> I am trying to achieve a fade in/out effect specifically for the background image of the Cover section. T ...

What is the best way to eliminate the underline text decoration from a link element?

Take a look at this JS Bin. I want to change the link Project name in there. By default, it is underlined when hovered over. How can I remove that effect? I attempted using a class project-name: a:hover, a:focus .project-name { text-decoration: non ...

Tips for connecting a suspended div below a Bootstrap 5 fixed navigation bar

I successfully implemented a sticky navigation using Bootstrap 5, and now I want to add a hanging div (.chat-tag) below the sticky nav for a chat feature. This "hanging tag" should stay attached to the sticky nav as the user scrolls down the page. It&apos ...

pressing a button unrelated to the 'close' button still triggers the close event

I have a notification bar that features a button in the center that links to another website. There is also a 'close' button on the far right. However, whenever I click the center button, it also triggers the close button. I tried moving the #cl ...

What are some strategies for increasing efficiency in my drag and drop process?

Update #2 Wow, transition was stuck at .35s. My CSS just wasn't updating properly :( UPDATE: Anyone know if requestAnimationFrame could help with this? I've got a rotating image reel and I want users to be able to swipe left or right to switch ...

Guide to positioning the layout inflater on the right side

I am facing an issue with the layout inflater where the inflated layout appears in the center of the page instead of the intended right corner placement. I have attempted to modify the gravity to right, but it did not resolve the problem. Below is a snipp ...

Fixed bar on top, revealed only when the scroll attempts to conceal it

I have placed a menu on the top section of my website, but not at the very top. I would like it to stick to the top of the page when the user scrolls down and disappears from view. However, if the title is still visible, I want the menu to remain below it ...

Sliding and repositioning elements using jQuery

My goal is to build a simple slideshow for learning purposes. I want the list items to slide automatically to the left in a continuous loop. I've written some code that makes the slides move, but I'm struggling to set the correct position for ea ...

Make the HTML element expand to the remaining height of the viewport

Need help with creating a section that automatically fills the remaining viewport height below the navigation bar. The section includes a centered div and background image, along with a button at the bottom for scrolling down by one full viewport height. H ...

Iterating through data to showcase vertical columns for a specific time span of 3 years, highlighting only the months with available data

If data has been available for every month over the past 3 years, I need it to be displayed in a specific format. You can refer to this example fiddle for reference: https://jsfiddle.net/bthorn/ncqn0jwy/ However, there are times when certain months may no ...

Need to style today's date and selected date differently using react datepicker

I am currently working with the React Datepicker and I am facing an issue where two different styles need to be applied for the current date and a selected date. Specifically, I have defined a style for the current date as well as a separate style for whe ...

Tips for ensuring smaller columns have the same height as their siblings

I'm facing an issue where I have a row with two columns dictating the height, but one of them is shorter than the others. How can I make the shorter column stretch to match the height of the row? This inconsistency in height is causing disruption to ...

Having trouble getting the form input max-width to work properly within a flex-box

My webpage features a header containing various icons, a title, and a search box that triggers an animation when the search button is clicked. While this setup works seamlessly on larger screens, I encounter issues on smaller screens. My goal is for the se ...

Positioning a fixed div within a responsive div using AngularJS and Bootstrap

I'm currently working on a page layout that consists of a fixed sidebar on the left side and a main container taking up the rest of the page on the right. Inside this right-side container, which is a div, there are 2 elements. <div class="col-sm-1 ...

How can I implement a scroll bar in Angular?

I am facing an issue with my dialog box where the expansion panel on the left side of the column is causing Item 3 to go missing or appear underneath the left column when I expand the last header. I am looking for a solution to add a scroll bar so that it ...

The overlay image is not positioned correctly in the center

I am struggling with positioning a play icon overlay on the image in my list-group-item. The current issue is that the icon is centered on the entire list-group-item instead of just the image itself. I am working with bootstrap 4.4.1. Here is the HTML str ...

Tips on how to select only the currently active tab and change its background color

I am currently troubleshooting the AJAX tabs functionality on my website. The issue I am facing is that the current code does not apply any styling to indicate an active tab. I believe I may need to use some JavaScript code to address this problem, but I ...

Utilizing jQuery to apply a class to an element and modify the CSS parameters with custom values simultaneously

Unsure if this idea is feasible, but I'll attempt to explain my requirements. I am interested in accomplishing something like the following: A CSS class with variables X, Y, and Z left undefined: .r {border-radius:Xpx;-webkit-border-radius:Ypx;-moz ...