Dynamic font size based on the size of the widget

Currently I am using a template widget to display date and time in HABpanel. Since I use different devices I’d like to create one widget for all use cases. That means the font size should automatically adapt to the dimensions of the widget.

I already found https://stackoverflow.com/questions/16056591/font-scaling-based-on-width-of-container and am currently using vw which displays the same relative font size no matter how big the screen is. However this does adapt to the widget size.

The current code from https://github.com/openhab/org.openhab.ui.habpanel/issues/293#issuecomment-366018495:

<div>
  <ds-widget-clock show-digital digital-format="'HH:mm:ss'" style="color: lightgray; font-size: 5vw; font-weight: bold;"></ds-widget-clock>
</div>
<div>
  <ds-widget-clock show-digital digital-format="'fullDate'" style="color: gray; font-size: 2.5vw;"></ds-widget-clock>
</div>
1 Like

Recently I found a possible way to achieve this. I looked at Custom widget: Current Weather and there is something used that can also be applied in my example.

I am now using

<div>
  <ds-widget-clock show-digital digital-format="'HH:mm'" style="color: lightgray; font-size: {{ (ngModel.sizeY * 1.5 > ngModel.sizeX) ? (ngModel.sizeX * 55/1.5) : (ngModel.sizeY * 55) }}px; font-weight: {{ ((ngModel.sizeX > 6) && (ngModel.sizeY > 4)) ? '250pt' : 'bold' }};"></ds-widget-clock>
</div>
<div>
  <ds-widget-clock show-digital digital-format="'EEE dd. MMM'" style="color: gray; font-size: {{ (ngModel.sizeY * 1.5 > ngModel.sizeX) ? (ngModel.sizeX * 20/1.5) : (ngModel.sizeY * 20) }}px;"></ds-widget-clock>
</div>

However the numbers used are trial and error and only working for this specific text, so the whole solution is not that nice. I’d like to have something that automatically adjusts the text size so it stays inside of the widget, regardless of the amount of letters etc.

1 Like

Hi All,

I had a similar problem. There is not way with pure HTML / CSS to dynamically size text in the way needed. The most common way to do it is to use Javascript / JQuery. However adding Javascript can be very cumbersome with HabPanel – particularly as Items change state.

The solution I went with was to use inline SVG images as a background for the DIV where the text needed to be displayed. Because the images are generated in-line in CSS, you can write whatever text you like into the image. Dont have access to my code at the moment, but basically, something like this:

<style>
.my-dynamic-text {
    background-image: url(".....<svg>......{{getItem(my_Item).name}}.....</svg>");
    ....
    width: 100%;
    height: 100%;
}
</style>
<div class="my-dynamic-text"></div>

Hope it helps.