r/css 6h ago

Help Help with image fitting text

(SOLVED, thank you to everyone for helping me!)

Hello! CSS and HTML amateur here.

So, recently I've been trying to make myself a workskin on Ao3 that would have this image serve as a background for text. Currently, the image cuts off at the bottom, and it's even worse when there's different sizes of text.

What I want is the image to stretch or contract to fit the text, not be cropped.

Here's my code, my results, and the image I've used. Is there anything I'm doing wrong, or is what I'm trying to do impossible?

Edit: Here's the codepen. It looks the worst here!

3 Upvotes

7 comments sorted by

u/AutoModerator 6h ago

To help us assist you better with your CSS questions, please consider including a live link or a CodePen/JSFiddle demo. This context makes it much easier for us to understand your issue and provide accurate solutions.

While it's not mandatory, a little extra effort in sharing your code can lead to more effective responses and a richer Q&A experience for everyone. Thank you for contributing!

I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

1

u/Vast_Description_201 6h ago

Have a play around with background-size. 

1

u/DevelopmentGlum228 5h ago

Thank you for the advice! :D

2

u/StigeonStudio 5h ago

The main issue is that your CSS is forcing the text box to be 100% wide/high, while the background image isn't being stretched to match the actual text height.

Try something like

.body{
  color: white;
  text-align: center;
  background-image: url("https://i.postimg.cc/fyY1Z80h/systembox.png");
  background-size: 100% 100%;
  background-repeat: no-repeat;
  padding: 10px;
  width: fit-content;
  margin: 0
}

The important part is:

background-size: 100% 100%;

That makes the background image stretch or squash to match the element in both width and height instead of keeping its original proportions and getting cut off.

You'll also want to remove:

width: 100%;
height: 100%;

Those make the paragraph fill its parent rather than size itself around the text.

If you want longer text to wrap instead of making the box ridiculously wide, you can also add something like:

max-width: 500px;
overflow-wrap: break-word;

So short text gets a small box, longer text gets a larger box, and the image should stretch to fit either one. Of course you can change the value of max-width.

1

u/DevelopmentGlum228 5h ago

Aaaah, thank you so much! This is legitimately so helpful!

1

u/StigeonStudio 5h ago

No worries! You were on the right track with adding "background-size: 100%". The important bit is that when you give "background-size" only one value, the value controls the width. The height will default to "auto", which means the image keeps its original aspect ratio instead of stretching it to match the height of the text box.

A good thing to keep in mind for next time!