Even tax-exempt nonprofits sometimes earn taxable income. If a nonprofit runs an "unrelated business" to raise money -- one that's not part of the core mission -- the unrelated business income is taxable. The IRS applies a similar rule to capital gains on the sale of real estate. The tax treatment of the gains depends on whether the property was part of the nonprofit's mission or unrelated. IRS Publication 598 gives the details.
Generally there's no tax on income, including gains from real estate, if the business activity is related to the organization's purpose. An art museum, for example, could run a movie theater showing art documentaries as part of its mission, but if it owns a theater running summer blockbusters, that's an unrelated activity. When the museum sold the theater, the tax treatment of any capital gains would depend on what it had been used for.
If the nonprofit uses the real estate purely for its mission -- a historic society that owns historic buildings, say -- there's no tax on the gains when the property is sold. If the nonprofit uses the property for an unrelated business, it pays tax, as described in Form 598. You use Form 990-T for your tax return. A nonprofit that uses the property for a mix of related and unrelated purposes has to allocate gain from the sale between the two. Any gain allocated to the unrelated business purpose is taxable. There are many exemptions and special cases, so you may need to consult with a tax professional to determine how the rules apply.