css ::after and ::before selectors go to the next line - how to prevent

961 views Asked by At

I have been trying to add an image next to my navigation menu using CSS pseudo selectors ::before or ::after.

.menu_container::before{
    content: "";
    background: transparent url('ISO.png') no-repeat;
    position:relative;
    float:right;
    width: 50px;
    height:100px;
} 

When i use above code, the image is positioned on a line before the actual menu. When I use the ::after selector it goes to the next line.

I have tried almost all the solutions given in this forum for similar issues. But nothing worked. Really appreciate your support.

Thanks heaps.

2

There are 2 answers

0
Suraj Rawat On

Try this.....

.menu_container{
     position: relative;
 }

.menu_container::before{
     position: absolute;
}

/* now u can change where ever you want your before , after div */

0
jbutler483 On

You would need to place the :before pseudo element in a way that it will always be positioned according to where the 'actual' element is.

So, to achieve this, you will need to first ensure your 'main' element is positioned relatively:

.menu_container{
    position:relative;
    display:inline-block; /*more than likely needed for elements*/
}

That's realistically the only required CSS you need on the parent for this to work.

For your pseudo element, you shouldn't look to use a float as that will take the pseudo out of the flow of the dom - we don't want that. We can to position it according to the next relatively positioned parent (which we have just made as the main element).

.menu_container:before{
    content: "";
    background: transparent url('ISO.png') no-repeat;
    position:absolute;
    top: 0;
    left:0;
    height:100%;
    width:50px;
} 

I would also suggest removing the double :: and replacing with a single : for better browser support (old IE doesn't like the double colon syntax).

So the Position:absolute will allow you to use the top:, left:, bottom: and/or right: properties to position it according to this relative parent.