The computations are somewhat similar to those in the other answers, but this solution also copes with unnumbered sections and long titles.
\documentclass[a4paper]{book}
\usepackage{lipsum}
\usepackage{titlesec}
\usepackage{xcolor}
\newsavebox{\sectionlabelbox}
\newlength{\sectionlabelwidth}
\colorlet{mygray}{gray!90}
\colorlet{myblue}{blue!80}
\newcommand{\sectionlabel}{%
\sbox{\sectionlabelbox}{\colorbox{mygray}{\strut\color{white}Section~\thesection}}%
\global\sectionlabelwidth=\wd\sectionlabelbox
\usebox{\sectionlabelbox}%
}
\newcommand{\sectiontitle}[1]{%
\colorbox{myblue}{%
\parbox[t]{\dimexpr\columnwidth-\sectionlabelwidth-2\fboxsep-0.5ex}{
\raggedright\strut\color{white}#1
}%
}%
}
\titleformat{\section}[hang]
{\large\bfseries\global\sectionlabelwidth=-0.5ex }%
{\sectionlabel}
{.5ex}
{\sectiontitle}
\begin{document}
\section{A test}
\setcounter{section}{9}
\section{Another test}
\section{Another test, but with a title that is so long it has to be
split across lines}
\section*{A further test}
\end{document}
Here's a modification where the grey box has the same vertical size of the blue box.
\documentclass[a4paper]{book}
\usepackage{lipsum}
\usepackage{titlesec}
\usepackage{xcolor}
\newsavebox{\sectiontitlebox}
\newlength{\sectionlabelwidth}
\colorlet{mygray}{gray!90}
\colorlet{myblue}{blue!80}
\newcommand{\sectiontitle}[1]{%
\settowidth{\sectionlabelwidth}{%
\colorbox{mygray}{\strut\color{white}Section~\thesection}%
}%
\sbox{\sectiontitlebox}{%
\colorbox{myblue}{%
\parbox[t]{\dimexpr\columnwidth-\sectionlabelwidth-2\fboxsep-0.5ex}{
\raggedright\strut\color{white}#1
}%
}%
}%
\colorbox{mygray}{%
\vrule height \dimexpr\ht\sectiontitlebox-\fboxsep\relax
depth \dimexpr\dp\sectiontitlebox-\fboxsep\relax
width 0pt
\color{white}Section~\thesection
}%
\hspace{0.5ex}%
\usebox{\sectiontitlebox}%
}
\newcommand{\sectionstartitle}[1]{%
\colorbox{myblue}{%
\parbox[t]{\dimexpr\columnwidth-2\fboxsep}{
\raggedright\strut\color{white}#1
}%
}%
}
\titleformat{name=\section}[hang]
{\large\bfseries}
{}
{0pt}
{\sectiontitle}
\titleformat{name=\section,numberless}[hang]
{\large\bfseries}
{}
{0pt}
{\sectionstartitle}
\begin{document}
\section{A test}
\setcounter{section}{9}
\section{Another test}
\section{Another test, but with a title that is so long it has to be
split across lines}
\section*{A further test}
\end{document}
\graybox
in the preamble. I think you should move the line\settowidth{\myl}{\graybox}
in the last argument of\titleformat
, before\colorbox{myblue}...
.\setcounter{section}{100}
changes\thesection
width.