I know the title of this question is stupid, but I couldn't come up with anything better. I have searched for hours on this topic, but either I search for something wrong, or else I have missed out on some CSS basics.
I have a container div with a 40x40px background-image placed in the top left corner. I want to align the top of the text from an h2 tag with the top of that background-image, which I have tried to do like this.
HTML:
<div id="container">
<h2 id="title">Lorem</h2>
</div>
CSS:
body {
font-family: Arial, Helvetica, sans-serif;
font-size: 13px;
}
#container {
background: url('test-icon.png') top left no-repeat;
margin: 200px auto; /* To center the container on the page*/
min-height: 50px;
padding-left: 50px; /* To prevent the text from "colliding with the background-image"*/
width: 300px;
}
#title {
font-family: "Arial Black", Arial, Helvetica, sans-serif;
font-size: 1.3em;
text-transform: uppercase;
}
I have used Eric Meyers CSS reset to get rid of browser specific styles, but have left this out in the above code.
I have created a live example
The problem is that the background-image and the top of the text from the h2-tag do not align - there is a small "margin" in the top of the h2 tag. This margin seems to change with the font size. When I use Google Chromes inspector, it tells me that the margin and padding of the h2 and div tag are all 0px. As browsers render fonts differently, I don't mant to mess around with negative margins in case it breaks the layout. Is there a way to "safely" get rid of this margin? To be totally clear, what I want to acheive is this.
I think your problem is the line-height
on the <h2>
. A bit of fiddling around tells me that you want it to be:
line-height: 10px;
You might need to use px
for your font-size
to get things to work consistently in various browsers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With