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:
w: Width of the input videoh: Height of the input videotw: Estimated width of the rendered textth: Estimated height of the rendered text
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:
box=1: Enables the background box.boxcolor=black@0.5: Sets the box color (e.g., black with 50% opacity).boxborderw=10: Adds padding (border width) around the text inside the box.
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.mp4Parameter Breakdown:
text='Top Center Caption': The string of text to render.fontcolor=white: The color of the text.fontsize=24: The size of the text in pixels.box=1:boxcolor=black@0.6:boxborderw=15: Configures a semi-transparent black background box with 15 pixels of padding around the text.x=(w-tw)/2: Centers the box horizontally.y=30: Positions the box 30 pixels down from the very top of the frame.