In the following image, the top text has regular spaces around the bold word
bar, whereas the bottom text includes the spaces in the bold styling:
I added red vertical marker lines so it's easier to see that the words don't line up perfectly. For some fonts, this doesn't seem to make a difference, however for others (like Avenir) it does matter.
Is there a general rule about which I should prefer? If I make a word bold, should I also make both the spaces around it bold?
(and if it doesn't broaden the question too much, what about italic text instead of bold text)?
No, the spaces should not be bold because that would be bad semantics. A word or run of words can be bolded, but spaces around a word cannot.
This is separate from any thoughts of visual design, and independent of any implementation. The semantics come from the writer. They are not up to the designer. The designer has visual design tools to do their visual design. Again, in any implementation.
In your example, the writer wrote:
foo **bar** baz
â€¦ shown here in Markdown, but it applies in any writing environment.
A writer would have no reason to bold the spaces because there is no semantic reason to bold the spaces. The bold text comes from the writers mind. They are bolding a word (or run of words) not bolding spaces.
So the HTML â€” example is in HTML because your example is in HTML, but this applies to any implementation â€” of the above Markdown is:
foo <b>bar</b> baz
â€¦ and it is after that when visual design begins.
If you look at an example using actual writing it is clearer:
Danger do not eat contents of packet.
â€¦ it is the word â€œDangerâ€ that has the bold emphasis. Nothing else.