Create a shape layer, from effects menu apply Slider with the following expression
- Apply the sliderto your shape element.
- Rename the slider to “Padding“.
- In Shaper object, go to Content > Rectangle 1 > Rectangle Path 1 > Size
- Alt + Click on Size.
- Apply the below code.
- Remember to rename your text layer to “Caption“.
// Define Variable
var x;
// Add padding to the shape object, if it has content
if(thisComp.layer("Captions").text.sourceText.value < 1) {x=0} else {x=35};
// Resize the shape based on the content
title = thisComp.layer("Captions").sourceRectAtTime();padding = effect("Padding")("Slider");[title.width+x+ padding, title.height + padding + 35]
Source