I wish to create section heading using titlesec
like image
But I have some difficulties in determining the width of remaining of line to include blue box containing section label, my method consist of subtracting length of gray box from textwidth
but it did not work.
\documentclass[a4paper]{book}
\usepackage{lipsum}
\usepackage[explicit]{titlesec}
\usepackage{xcolor}
\newlength{\myl}
\colorlet{mygray}{gray!90}
\colorlet{myblue}{blue!80}
\newcommand{\graybox}{\colorbox{mygray}{\strut \color{white}Section~\thesection}}
\settowidth{\myl}{\graybox}
\titleformat{\section}[hang]{\large\bfseries}%
{\graybox}{.5ex}{\colorbox{myblue}{\makebox[\dimexpr \linewidth-\myl-2\fboxsep-.5ex][l]%
{\strut \color{white}\large\bfseries #1}}}
\pagestyle{empty}
\begin{document}
Best Answer
The computations are somewhat similar to those in the other answers, but this solution also copes with unnumbered sections and long titles.
Here's a modification where the grey box has the same vertical size of the blue box.