Center Text at Top of Video with FFmpeg Drawtext

This article explains how to position a text box at the top center of a video using mathematical calculations within the FFmpeg drawtext filter. You will learn the exact formulas required to calculate horizontal centering, apply vertical top-padding, and style the surrounding text box for optimal readability.

The Mathematical Formulas

To position text accurately, FFmpeg provides built-in variables representing the dimensions of both the video and the rendered text. To place the text box at the top center, you must calculate the horizontal coordinate (x) and the vertical coordinate (y) using these variables:

Horizontal Calculation (Centering)

To center the text horizontally, subtract the width of the text from the width of the video, and divide the result by two:

x=(w-tw)/2

Vertical Calculation (Top Alignment)

To place the text at the top, you could set y=0. However, this places the text box flush against the top edge of the video frame. To make it visually appealing, add a small pixel offset (padding) from the top, such as 20 or 30 pixels:

y=20

Alternatively, you can use a percentage of the video height for dynamic scaling:

y=h*0.05

Creating the Text Box

To draw a background box behind the text, you must enable the box parameter and define its styling properties inside the drawtext filter:

FFmpeg Command Example

Combine the positioning calculations and the box styling parameters into a single drawtext video filter (-vf):

ffmpeg -i input.mp4 -vf "drawtext=text='Top Center Caption':fontcolor=white:fontsize=24:box=1:boxcolor=black@0.6:boxborderw=15:x=(w-tw)/2:y=30" -codec:a copy output.mp4

Parameter Breakdown: