Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to increase margins around a word except at the edges of a line

I am using <code> with extra CSS. I'd like to increase the left/right margins around

code {
  margin-left: 10px;
  margin-right: 10px;
}
This word is a <code>reserved</code> word.

That works fine usually, but if the word is at the beginning of a line, it has the awkward extra margin to the left that I don't want. Example:

code {
  margin-left: 10px;
  margin-right: 10px;
}
This word is a <br><code>reserved</code> word.

To be clear, the <br> was only for the above example... I don't know when the <code> is at the beginning of the line, it depends on how it is folded (for a given window width).

CSS word-spacing seems like it could be the fix here, but it appears only to be inter-word spacing, so it doesn't work.

Is there a way to accomplish this using CSS?

like image 234
Brian Avatar asked Mar 05 '16 15:03

Brian


1 Answers

I can only find 2 3 ways to solve this, unless you want a script running through the text and count lines, and that is by wrapping the rest of the text too,

span {
  margin-right: 10px;
}
code {
  margin-right: 10px;
}
<span>This word is a </span><code>reserved</code><span> word.
This word is a <br></span><code>reserved</code><span> word.
This word is a </span><code>reserved</code><span> word.</span>

or each word directly in front of the reserved word.

span {
  margin-right: 10px;
}
code {
  margin-right: 10px;
}
This word is <span> a </span><code>reserved</code> word.
This word is <span> a </span><br><code>reserved</code> word.
This word is <span> a </span><code>reserved</code> word.

If the in front word's element would differ frequently (like span, b, i), here is a CSS rule variant to cover that.

code {
  margin-right: 10px;
}
*:not(br) + code {
  margin-left: 10px;
}
This word is <span> a </span><code>reserved</code> word.
This word is <i> a </i><br><code>reserved</code> word.
This word is <b> a </b><code>reserved</code> word.

Here is yet another way, though it as a minor flaw where it won't break the line properly, as the reserved word need to be without a space in the markup to the closest word in front. It does have another benefit though, of a minimal markup.

code {
  margin: 0 10px;
}
code:before,
code:after {
  font-size: 0px;
  content: ' ';
}
This word is a<code>reserved</code> word.
This word is a<code>reserved</code> word.
This word is a<code>reserved</code> word.
This word is a<code>reserved</code> word.
This word is a<code>reserved</code> word.
This word is a<code>reserved</code> word.
like image 161
Asons Avatar answered Sep 29 '22 06:09

Asons