How can you make a div border to appear the way background-color does (very close to the text) like here?
When I add borders, the whole div just scales to the h tag margins I think?
I don’t want to touch h tag margin. Or is it the only way?
.text-1 {
background-color: lightblue;
}
.text-2 {
background-color: lightgray;
border: solid 3px black;
}
<div class="container">
<div class="text-1">
<h2>Menu</h2>
<p> today </p>
<p> now </p>
<p> tomorrow </p>
</div>
<br>
<br>
<div class="text-2">
<h2>Menu</h2>
<p> today </p>
<p> now </p>
<p> tomorrow </p>
</div>
</div>
simplified issue – https://jsfiddle.net/Lnjaz3rs/17/
3
Answers
You can remove the margins on the first and last elements within the div with:
Try using a
box-shadow
instead.This is the intended way for h2 to be handled as the element container includes that space above and below. Background only covers actual displayed content within a container, hence why it’s covering from and up to actual letters being displayed. Border displays a line on the outer part of the container the elements are in, so the whole div is bordered, and this includes the spaces contained in it as well.
The easiest way to make the border closer to the content is through a negative padding, something like
padding: -1em 0;
will take space away from top and bottom,but won’t trim your border away. Adapt it to your needs. In any case you’ll need to mess with either the div or the elements to make it display in the way you want while still keeping the border.