0

I am having a h3, which may have long or sometimes short text. I have manually set the font-size of the h3 to 3rem. But when it is a long text, the text starts to overflow the parent div. When it is a short text, it appears to be small (font-size). How can I make the h3's font-size to automatically scale according to the parent div? Note that the parent div has a fixed height and width and has nothing to do with the screen size.

<div id="book_div">
  <div className="book-div_container">
    <p className="book-div_author">{author}</p>
    <div className="book_div_data">
      {series && <h2 className="book_div_series">{series}</h2>}
      <h3 id="bookdivtitle" className="book_div_title">
        {title}
      </h3>
    </div>
  </div>
</div>

 #book_div {
  height: 18.875rem;
  width: 12.25rem;
  background-color: #857073;
  color: white;
  font-family: "Noto Sans JP", sans-serif;
  padding: 1rem;
  box-shadow: 0 0 10px grey;
}

.book-div_container {
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.book-div_author {
  font-size: 100%;
}

.book_div_data {
  padding-top: 3rem;
}
.book_div_series {
  font-size: 1.5rem;
  text-align: center;
}

.book_div_title {
  text-align: center;
  word-break: break-all;
}

Edit: CodeSandbox link is here.

Any help is greatly appreciated !
Thanks!

Ajit Kumar
  • 367
  • 1
  • 10
  • 35
  • `em` is used for scaling according to parent size & `rem` is used for scaling according to root element, i.e, `html` – deadcoder0904 Jul 31 '21 at 09:38
  • Thanks! I changed it into `3em`. But it overflows the parent `div` if it is a large text – Ajit Kumar Jul 31 '21 at 09:41
  • Make a JSFiddle with some text that shows what happens :) – deadcoder0904 Jul 31 '21 at 09:49
  • Thanks! Here it is: https://codesandbox.io/s/cool-bash-j9rys?file=/src/App.js – Ajit Kumar Jul 31 '21 at 12:47
  • What do you want to happen? If you want it to stop overflowing the boundary, then use overflow property. If you want it to follow parent's `font-size` then put `font-size` on the `div` of `h3` in `px`. You can't scale `h3` automatically on parent's text side like if you want long text to be smaller in size & small text to be bigger in size. Maybe you can in JS but not CSS I think :) – deadcoder0904 Jul 31 '21 at 13:42
  • Thanks! If I can go with js how can I continue ? – Ajit Kumar Jul 31 '21 at 13:47
  • Check if the text is long, then assign it a small font-size (16px). If it is short, then assign it a large font-size (20px) & this requires lots of trial & error but I don't understand why would you want to do such thing but that's the solution. You can also check out https://github.com/rikschennink/fitty – deadcoder0904 Jul 31 '21 at 13:48
  • Because, sometimes the `title` will be short, so I want the text to fit the `div`. Otherwise, if the text is long, I want the `title`'s font-size to reduce....:) – Ajit Kumar Jul 31 '21 at 13:54

0 Answers0