tdrsam tdrsam - 1 year ago 124
CSS Question

Alternative to negative margins

I'm looking for an alternative to using negative margins because I know they aren't considered "cool", and that they're considered hacky.

I'm starting a new site in WordPress and I need to add two images to every page. The images have to be linked and the link has to be different on every page so I can't add the images to a menu or a widget.

When I add them to the content of the page they display below the header, but I need them inside the header. I've positioned them like so:



And then I added a negative margin-top in the dev tools and they display inside the header where I need them, but I'm wondering if there's an alternative to using the negative margin.

This image shows what I'm doing. The English flag has the negative margin but the Chinese flag displays below the header because it's only got positioning, which places it inside the same div, not at the top of the page.

enter image description here

Working Sample

Answer Source

Nothing wrong with negative margins if used appropriately. It's all about using the right tool for the job. In this case you're doing it a bit wrong.

Firstly if positioning multiple elements say your flags to the top right you want to be able to easily add/remove them without adding CSS so wrap them in a container that's absolutely positioned instead of positioning each flag on it's own OR float a container to the right if it's appropriate.


<div class="flag-container">
    <img class="alignright size-full wp-image-19 zhflag" src="" alt="Chinese Language Button" width="50" height="35">
    <a href=""><img class="alignright size-full wp-image-18 enflag" src="" alt="English Language Button" width="50" height="35"></a>


    position: absolute;
    right: 0; 
    top: -65px;

And remove all the rules for .zhflag and .enflag as none of them are now needed.

It's probably be better to move the flag-container in a container with the nav that's relatively positioned and 100% wide so that things are grouped better and to avoid layering issues particularly in older browsers.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download