简体   繁体   中英

How do I dynamically change margin depending on an absolutely positioned elements height

I am trying to dynamically change the margin-top of an element depending on the height of another absolutely positioned image.

Before anyone asks, it has to be absolutely positioned because of other reasons so I can't just make it relative.

I am able to change the margin only when I type in an absolute value such as "200px". However, when I try to use a variable to dynamacally change the margin-top on every window rezise, it simply don't give the element any margin at all.

Any help would be helpful. Thank you in advance!

var element;
var textIntro;
var newMargin;

function setMargin() {
    element = document.getElementById("cover1");
    newMargin = element.style.height;
    document.getElementById("TextIntro").style.marginTop = newMargin;
}

Hope it will help you this Js:

setMargin();

function setMargin() {
    element = document.getElementById("cover");
    newMargin = element.offsetHeight;
    document.getElementById("cover1").style.top = newMargin +"px";
}

DEMO

 var element; var textIntro; var newMargin; setMargin(); function setMargin() { element = document.getElementById("cover"); newMargin = element.offsetHeight; document.getElementById("cover1").style.top = newMargin +"px"; }
 body{ margin: 0; } body > div { position:relative; padding:20px; height:500px; width: 90vw; background-color:red; } body > div > div { position:absolute; display:block; width:calc(100% - 80px); /* Padding parent + this object */ margin-top: 20px; padding: 0 20px 0 20px; } body > div > #cover{ background-color:green; height: 100px; top: 0; } body > div > #cover1{ background-color:blue; height:200px; } body > div > #cover2{ background-color:orange; }
 <div> <div id="cover"></div> <div id="cover1"></div> </div>

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