tdrsam tdrsam - 1 month ago 23
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:

.enflag{
position:absolute;
top:0;
right:0;
}

.zhflag{
position:absolute;
top:1%;
right:1%;
}


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

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.

HTML

<div class="flag-container">
    <img class="alignright size-full wp-image-19 zhflag" src="http://rmbpay.com.au/tmp/wp-content/uploads/2016/11/Zh-Flag-s.png" alt="Chinese Language Button" width="50" height="35">
    <a href="http://rmbpay.com.au/tmp/"><img class="alignright size-full wp-image-18 enflag" src="http://rmbpay.com.au/tmp/wp-content/uploads/2016/11/british-flag-s.png" alt="English Language Button" width="50" height="35"></a>
</div>

CSS:

.flag-container{
    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.