vimtricks.wiki Concise Vim tricks, one at a time.

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 (or ce) — the :center Ex command; centers each line by adding leading spaces
  • [width] — optional column width (defaults to textwidth or 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

  • :center works with any range, not just visual selections — use :%center 78 to center the entire file
  • :'<,'>right 80 right-aligns selected lines to column 80 without a plugin
  • :'<,'>left strips leading whitespace from selected lines, effectively left-aligning them
  • Combine with :'<,'>!awk '{...}' for more advanced alignment if you have external tools
  • :set textwidth=72 before using :center with no argument to control the default width

Next

How do I use capture groups in Vim substitutions to rearrange or swap matched text?