How do I center-align a block of selected lines at a specific column width in Vim?
Answer
:'<,'>center
Explanation
After making a visual selection, typing : automatically inserts '<,'> to scope the command to the selection. Running :'<,'>center [width] centers each selected line within the given column width (default: textwidth or 80 if unset). This is a built-in Ex command that requires no plugins.
It is especially useful for centering comment banners, section headers, or ASCII art without manual counting.
How it works
:'<,'>— the visual range (inserted automatically when you press:in visual mode)center(orce) — the:centerEx command; centers each line by adding leading spaces[width]— optional column width (defaults totextwidthor 80)
The command pads the line with leading spaces so the content is horizontally centered within the specified width.
Example
Starting text:
Section Header
Subtitle Here
Select both lines with Vj, then run :'<,'>center 60:
Section Header
Subtitle Here
To right-align instead, use :'<,'>right [width]. To left-align (strip leading spaces), use :'<,'>left.
Tips
:centerworks with any range, not just visual selections — use:%center 78to center the entire file:'<,'>right 80right-aligns selected lines to column 80 without a plugin:'<,'>leftstrips leading whitespace from selected lines, effectively left-aligning them- Combine with
:'<,'>!awk '{...}'for more advanced alignment if you have external tools :set textwidth=72before using:centerwith no argument to control the default width