Diabetes is a well-known risk factor for dementia. We investigated the association between (pre)diabetes and older brain age and whether this can be attenuated by modifiable lifestyle behaviors. The study included 31,229 dementia-free adults from the UK Biobank between the ages of 40 and 70 years. Glycemic status (normoglycemia, prediabetes, or diabetes) was ascertained based on medical history, medication use, and HbA1c measured at baseline. Information on cardiometabolic risk factors (obesity, hypertension, low HDL, and high triglycerides) and lifestyle behaviors (smoking, drinking, and physical activity) was also collected at baseline. Participants underwent up to two brain MRI scans over 11 years of follow-up. Brain age was estimated using a machine learning model based on 1,079 brain MRI phenotypes and used to calculate brain age gap (BAG; i.e., brain age minus chronological age). At baseline, 13,518 participants (43.3%) had prediabetes and 1,149 (3.7%) had diabetes. Prediabetes (β = 0.22 [95% CI 0.10, 0.34]) and diabetes (2.01 [1.70, 2.32]) were both associated with significantly higher BAG, and diabetes was further associated with significant increase in BAG over time (0.27 [0.01, 0.53]). The association between (pre)diabetes and higher BAG was more pronounced in men and in people with two or more cardiometabolic risk factors. In joint exposure analysis, having a healthy lifestyle (i.e., no smoking, no heavy drinking, and high physical activity) significantly attenuated the diabetes-BAG association. Diabetes and even prediabetes are associated with accelerated brain aging, especially among men and people with poor cardiometabolic health. However, a healthy lifestyle may counteract this.