Layer setup

This requires two layers stacked in a specific order. The expressions reference layers by index offset, so the order matters.

Timeline stack (top to bottom)
n Background rectangle (Shape Layer) Shape ← expr on Size
n+1 Subtitle text (Text Layer) Text ← expr on X Position

The rectangle uses index-1 to look at the text layer below it. The text uses index+1 to look at the rectangle above it.

Expression 1 — Box size

Paste this on the Rectangle Path > Size property of the background shape layer:

Rectangle Size · After Effects
margin     = 33;
text_width = thisComp.layer(index-1).sourceRectAtTime().width;
text_height= thisComp.layer(index-1).sourceRectAtTime().height;
box_width  = text_width  + margin*2;
box_height = text_height + margin*2;
[box_width, box_height]

Expression 2 — Text centering on scale

Paste this on the Transform > X Position property of the text layer. It compensates for the anchor point shift when the box scales in from the side:

X Position · After Effects
linear(thisComp.layer(index+1).transform.scale[0], 0, 100, value-50, value)

Adjusting the margin

Change the margin value in Expression 1 to control the padding around the text. 33 is a comfortable default — increase it for a looser look, decrease for tighter.