0

I have an image inside a container. The image should always be at full browser width (100vw). As my layout is responsive, and the container has a fixed width at a certain point (45em), I can't simply use negative margins. So I got an idea, but as a novice I can't seem to achieve it...

This is what I want to do:

  • Check the body width
  • Check the container width
  • Subtract the element width from the body width
  • Divide this number in two
  • Add this number as a negative margin to an element

This is what I got so far...

var bodyWidth = $('body').width(); //Check the body width
var elemWidth = $('#content').width(); //Check the container width
var margin = bodyWidth-elemWidth; //Subtract the element width from the body width

I still need to divide the number in two, and add this number as a negative margin to an element.

Help is much appreciated.

1
  • Have you tried: $("#yourElement").css("margin-left:" + margin/2 + "; margin-right:" + margin/2); Commented May 19, 2015 at 8:54

1 Answer 1

1

You're on the right track.

var bodyWidth = $('body').width(); //Check the body width
var elemWidth = $('#content').width(); //Check the container width
var margin = bodyWidth-elemWidth; //Subtract the element width from the body width
var dividedMargin = margin / 2; // Divide the margin by 2
var negativeMargin = dividedMargin * -1; // set number to negative number
$(element).css("margin", negativeMargin); // replace element by the element name you want to apply this to.

You can also replace margin by margin-left, margin-right,margin-top or margin-bottom.

Sign up to request clarification or add additional context in comments.

1 Comment

You're welcome! Keep in mind that you can keep this in one line too, so you don't necessarily need 5 variables. My answer does make it more readable than keeping it in one line.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.