Invisible flag of death
Wikipedia says that the tradition of flying the flag at half-mast began in the 17th century. According to some sources, the flag is lowered to make room for an “invisible flag of death” flying above.
The US Flag Code
Flying the US flag at half-staff (or half-mast for ships) as a sign of mourning for a national figure, hero, fallen warrior or a tragedy is an old tradition. And not just in the USA. It is also practiced in other countries. In the US, the practice began following the death of George Washington in 1799 when the Navy Department ordered ships to wear their colors half-mast high.
Flags continued to be flown at half-staff or half-mast afterward, including following the assassination of Abraham Lincoln. In 1915 President Woodrow Wilson ordered executive offices closed and flags flown at half-staff to commemorate the 50th anniversary of Lincoln’s death.
It’s a code, not a law
There is a US flag code that stipulates some aspects of flying the official US flags. This code includes the half-staff routine. It should be noted that the US Flag Code and the rules for half-staff flags are not laws. You cannot be arrested for violations.
Flags may be ordered to half-staff and half-mast by the President of the United States, a state governor or the mayor of the District of Columbia.
There are websites, including one started after the US 9/11 attacks https://flagsexpress.com/, that keeps a list of all proclamations in the US of when flags should be lowered.
In witness whereof
A somewhat recent reason why flags are ordered half-staff in the US is in response to a few of the now common mass casualty shootings taking place at schools, places of worship, or workplaces. Which ones are selected for this treatment seems arbitrary though. Mind you, I can see that commemorating all such shootings in this way would have the flags half-staff permanently!
A Proclamation on Honoring the Victims of the Tragedy in Lewiston, Maine
[…]
IN WITNESS WHEREOF, I have hereunto set my hand this twenty-sixth day of October, in the year of our Lord two thousand twenty-three, and of the Independence of the United States of America the two hundred and forty-eighth.