Given a phrase in the middle of which TeX will place a return carriage, if we place this phrase within a \colorbox, TeX no longer places the return carriage and the phrase protrudes in the margin. Is there a way around this or am I missing something trivial?


1 Answer 1


Set your content inside a box that has the appropriate width, and place that box inside a \colorbox:

enter image description here



  \colorbox{#1}{\parbox{\dimexpr\linewidth-2\fboxsep}{\strut #2\strut}}%


Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec imperdiet elementum mi, 
sed fermentum metus accumsan vel. Aliquam eu lobortis metus, sed venenatis odio. 
Pellentesque ornare nibh augue, sit amet feugiat velit cursus ut. 

\cbox{In suscipit mattis nunc, vel sagittis risus pulvinar sit amet. Proin faucibus, 
neque vitae euismod interdum, nulla arcu semper massa, vitae fermentum turpis mi non 
lectus. Donec sed arcu placerat, tristique eros sit amet, varius tellus.}

Nullam varius tincidunt fermentum. Vivamus auctor, nunc vitae luctus semper, tortor 
purus efficitur nunc, ut consequat leo ligula quis urna. Aliquam vel nunc leo. 
Phasellus euismod lacus quam, vel elementum mi euismod vel.

\cbox[blue!30]{Cras vel urna eget sem 
tristique malesuada eget et ligula. Sed vitae lectus eleifend, consectetur diam quis, 
tristique enim. Phasellus ullamcorper dui rutrum, consectetur mauris eu, elementum 
sapien. Ut viverra imperdiet lacinia.}

  • Does not do what I would like. In your example, instead of including the whole fourth paragraph in the \cbox, include just "Sed vitae lectus eleifend". Then, eleifend protrudes in the margin and the box goes at infinitum to the right. What I would like is "Sed vitae lec-" on the first line of the fourth paragraph and "tus eleifend" in the second line to be both in colorboxes.
    – schremmer
    May 19, 2016 at 4:12
  • @schremmer: Then your question would be a duplicate of Cool text highlighting.
    – Werner
    May 19, 2016 at 4:20
  • Well, yes and no because while soul's \hl (Caramdir's answer) does indeed almost exactly what I want, I do not see in the doc, page 47, how to choose the color on the spot the way I can do with \colorbox. The Cool text highlighting question is really about tikz which I would rather not use as my setup is already quite heavy. Not to mention that Spector-Zabusky's four caveats are forbidding.
    – schremmer
    May 19, 2016 at 5:07
  • @schremmer: You can define yourself a command like \hl which accepts an argument to set the color. May 19, 2016 at 7:50
  • @ Ulrike Fischer Of course, that would do it but I do not know how to do that! And, I found out, \hl does not accept math so ...
    – schremmer
    May 19, 2016 at 13:08

Not the answer you're looking for? Browse other questions tagged .