Home > OS >  HTML/CSS Question: How can I make text automatically shrink and stay within a container?
HTML/CSS Question: How can I make text automatically shrink and stay within a container?

Time:05-31

I'm new to coding and have managed to make the image auto resize when changing the browser width, but the text has a mind of its own - any help would be much appreciated!

Here is my HTML: I have display: flex on the container to make the img left and the text content right within the container.

HTML

<div >
    <img  src="resources\images\banner.jpg" alt="">
    <div >
        <h2>Learn something<br>new everyday</h2>
        <p>Lorem ipsum dolor sit amet,<br>consectetur adipiscing elit.</p>
        <p ><a href="#">Start here</a></p>
    </div>
</div>

CSS:

.learn-container {
    display: flex; 
    background-color: lightgray;
    width: 100%;
}

.banner-img {
    width: 60%;
    height: 100%;
    padding: 32px 24px;
}

.learn-content {
    font-size: 42px;
    align-self: center;
    padding: 24px;
    margin: 0;
}

.start {
    color: white;
    background-color: rgb(71, 71, 71);
    text-align: center;
    padding-top: 8px;
    padding-bottom: 8px;
    font-size: 36px;
    width: 60%;
}

CodePudding user response:

Responsive text with css only is always a bit tricky, but you do have some options these days. You might consider using viewport units vw instead of a fixed pixel size. This is essentially "3% of the browser width". It's not suited for all cases but with a bit of trial and error you can get a decent approximation.

.learn-content {
    font-size: 3vw;
    align-self: center;
    padding: 24px;
    margin: 0;
}

Try this snippet. I've put it in codepen so you can more easily resize the window: https://codepen.io/29b6/pen/dydmWRp

Here's an MDN article on CSS units and how they work: https://developer.mozilla.org/en-US/docs/Learn/CSS/Building_blocks/Values_and_units

If you want to go further, there have been various javascript libraries over the years for just this sort of thing. The most actively maintained one as of right now seems to be Fitty.

If you want a history lesson in this area check out fittext.js!

CodePudding user response:

When changing font size you should avoid using purely vw units because there are accessbility issues around zooming in with the browser on smaller screen sizes (e.g phones).

In modern CSS you can use the clamp() function, this takes a min, a fluid and a max value. In the code it looks like this:

h2 {
  font-size: clamp(2rem, 6vw, 4rem);
}

It locks the sizing in at 2rem on small screens and 4rem on large screens, when the 4rem value becomes more than 6vw, the fluid middle value clicks in until that value hits the equivalent of 2rem or less. Obviously play around with these values until you get something you like in terms of sizing.

Codepen link: https://codepen.io/thechewy/pen/poaLPpY

  • Related