A time-fractional initial–boundary value problem Dtαu−Δu=f, where Dtα is a Caputo fractional derivative of order α∈(0,1), is considered on the space–time domain Ω×[0,T], where Ω⊂Rd (d≥1) is a bounded Lipschitz domain. Typical solutions u(x,t) of such problems have components that behave like a multiple of tα as t→0+, so the integer-order temporal derivatives of u blow up at t=0. The numerical method of the paper uses a standard finite element method in space on a quasiuniform mesh and considers both the L1 discretisation and Alikhanov’s L2-1σ discretisation of the Caputo derivative on suitably graded temporal meshes. Optimal error bounds inH1(Ω) are proved; no previous analysis of a discretisation of this problem using finite elements in space has established such a bound. Furthermore, the optimal grading of the temporal mesh can be deduced from our analysis. Numerical experiments show that our error bounds are sharp.