BACKGROUND: The relative impact of immune deficiency and lifestyle-related factors on risk of cancer in the HIV-infected population is controversial. We aimed to estimate the population-attributable fractions (PAFs) associated with smoking, being HIV-infected and with immune deficiency. METHODS: In a Danish, nationwide, population-based cohort study (1995-2011), incidences of cancer were compared between an HIV-infected cohort and a population-based matched cohort in analyses stratified on cancer category, smoking status and for HIV patients: low CD4 cell count. RESULTS: We included 3503 HIV patients [baseline CD4+ 450 cells/μl (inter-quartile range 310-630)] and 12,979 population controls. Smoking-related and virological cancers accounted for 23 and 43% of cancers in the HIV-infected population. The risk of these cancers were higher among HIV patients compared to controls [incidence rate ratio (IRR) 2.8, 95% confidence interval (CI) 1.6-4.9; and IRR 11.5, 95% CI 6.5-20.5], whereas the risk of other cancers did not differ (IRR 1.0, 95% CI 0.7-1.3). Non-smoking HIV patients did not have increased risk of non-virological cancers compared to non-smoking controls (IRR 1.2, 95% CI 0.7-2.1). The PAFs of cancer associated with smoking and with being HIV-infected were 27 and 49%, respectively. For cancers not strongly related to smoking or viral infections, the PAFs associated with being HIV-infected and with immune deficiency were 0%. CONCLUSION: The risk of cancer is increased in HIV patients compared to the background population. In absence of smoking, the increase in risk is confined to cancers related to viral infections, whereas the risk of other cancers is not elevated and does not seem to be associated with immune deficiency.