[Tex/LaTex] Boxed section heading style

sectioningtitlesec

I'd like the section title to look just as it does by default, except the following changes:

  • No spacing (before/after)
  • Text is inside black filled box
  • Text color is white

I've tried to use the titlesec package as done in the firt answer to the following question:

How to place a shaded box around a section label and name

However, I'm really having a hard time getting things to work with titlesec (it's not so intuitive in it's settings for me).

Best Answer

Here is a solution

\documentclass{article}
\usepackage{mwe}

\usepackage{xcolor}
\makeatletter
\renewcommand\section{\@startsection {section}{1}{\z@}%
                                   {0pt}%
                                   {0pt}%
                                   {\normalfont\Large\bfseries\mybox}}
\makeatother

\newcommand*{\mybox}[1]{%
    \noindent\colorbox{blue!20}{%
        \parbox{\dimexpr\columnwidth-2\fboxsep\relax}{%
            \textcolor{white}{#1}}}}

\begin{document}
\lipsum[1]
\section{Foo bar baz bla bla}
\lipsum[1]
\end{document}

Update if we need some vertical space before and after

\renewcommand\section{\@startsection {section}{1}{\z@}%
                                   {-3pt}%
                                   {3pt}%
                                   {\normalfont\Large\bfseries\mybox}}

enter image description here

Related Question