简体   繁体   中英

Subtract element width from body width, and add as margin to element

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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM