Nineteen people have been killed by gunmen who stormed Kabul University before engaging security forces in an hours-long battle.
A spokesman for the Afghan interior ministry said the attack on Monday was eventually stopped when three gunmen were killed.
At least 22 people were wounded, the interior ministry said.
The attack began around the time government officials were expected to arrive at the campus for the opening of an Iranian book fair.
All of the dead were students, including 10 women, a Kabul police spokesman told the AFP news agency.
The Taliban denied involvement and condemned the attack.
The Islamic State group has targeted education centres in Afghanistan in recent years, including an attack outside a tuition centre in Kabul last month that left 24 people dead. The group also claimed responsibility for a 2018 attack in front of Kabul University in which dozens were killed.
Video footage from the university campus on Monday showed students running away from the site with the sound of gunfire in the background. Some scaled walls in an effort to escape. One of the attackers detonated explosives, an Interior Ministry spokesman said.
"They were shooting at every student they saw. They even shot at the students who were running away," witness Fathullah Moradi told Reuters news agency.
Fraidoon Ahmadi, a 23-year-old student, was in class when the gunfire started: "We were very scared and we thought it could be the last day of our lives.... Boys and girls were shouting, praying and crying for help," he told AFP.
He and other students waited two hours until they were rescued, he added.
Violence in Afghanistan has worsened in recent months even as the Taliban conduct peace talks with the government in Doha, Qatar.
A senior UN official told the BBC last week that al-Qaeda was still "heavily embedded" within the Taliban, despite assurances from Taliban officials to the US that it would sever ties with the terror group.
- BBC