19

I've got an icon, like this:

<div class="mydiv">
   <i style="position: relative; top: 3px;"></i>
</div>

I want to move the icon down by 3 pixels, which works. But the div still has a greater height to it because the icon is technically expanding the height of the line. How do I make the icon not affect the layout at all, and not make the div bigger in height?

0

3 Answers 3

40

http://www.w3.org/TR/css3-positioning/#rel-pos

6.1. Relative positioning

A relatively positioned box keeps its normal flow size, including line breaks and the space originally reserved for it.

Basically a relatively positioned element still affects the surrounding elements. You're looking for position: absolute, but heres a trick from the same document

...
A relatively positioned box establishes a new containing block for absolutely positioned descendants. (This is a common use of relatively positioned boxes.) The section on containing blocks explains when a relatively positioned box establishes a new containing block.

So by setting the parent to position: relative you turn it into a containing block, which means that absolutely positioned elements contained within will be positioned relative to the edges of the parent rather than the root containing block (the window).

Hello World. 
<span style="position: relative; background-color: red;">
    This will be shown inline
    <span style="position: absolute; top: 100%; left: 0px;">
        This will be below
    </span>
</span>

0
8

You should make the parent's position relative and the actual element absolute.

<div class="mydiv">
    <i style="position: absolute; top: 3px;"></i>
</div>

.mydiv {
    position: relative;
}
1
  • Thanks, this also works. The other answer is more informative though so I accepted it :) Commented Jun 1, 2015 at 19:15
0

why not fix it with negative margin?

<div class="mydiv">
   <i style="position: relative; top: 3px; margin-bottom:-3px;"></i>
</div>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.