2016-11-22 119 views
1

我对定位元素有一个讨厌的问题: 所以我有一个孩子,需要有全屏宽度,而不是相对父母的。设置相对父宽度较小时的绝对元素全宽度为100%

body{ 
 
    padding: 10px; 
 
} 
 
.container{ 
 
    position:relative; 
 
    width: 400px; 
 
    border: 1px solid red; 
 
    padding: 15px; 
 
} 
 
.panel{ 
 
    position:relative; 
 
    width:200px; 
 
    margin: 0 auto; 
 
    height:40px; 
 
} 
 
.panel-body{ 
 
    position: absolute; 
 
    width:100%; 
 
}
<div class="container"> 
 
    <div class="panel panel-warning"> 
 
    <div class="panel-body"> 
 
     A Basic Panel 
 
    </div> 
 
    </div> 
 
</div>

所以问题是如何使panel-body中的所有其他元素的前面,并从屏幕不从父相对设置宽度100%,但是100%。 The html structure cannot be modified.

fiddle:

+0

'如何将面板主体放在所有其他元素前面,请使用[css z-index](http://www.w3schools.com/cssref/pr_pos_z-index.asp)。至于使一个孩子比它的父母检查更广泛[this](http://stackoverflow.com/questions/5581034/is-there-are-way-to-make-a-child-divs-width-wider-than -the-parent-div-using-css)链接。 –

+1

你可以在'.panel-body'上设置'position:fixed'而不是'absolute'。 –

+1

@MuhammadUsman这将工作,直到你必须滚动 – Keith

回答

2

这似乎工作,我想我侥幸它虽然。

body{ 
 
    padding: 10px; 
 
} 
 
.container{ 
 
    position:relative; 
 
    width: 400px; 
 
    border: 1px solid red; 
 
    padding: 15px; 
 
} 
 
.panel{ 
 
    position:relative; 
 
    width:200px; 
 
    margin: 0 auto; 
 
    height:40px; 
 
} 
 
.panel-body{ 
 
    position: absolute; 
 
    margin-left: calc(-50% - 20px - 15px); 
 
    width:100vw; 
 
    background-color: yellow; 
 
}
<div class="container"> 
 
    <div class="panel panel-warning"> 
 
    <div class="panel-body"> 
 
     A Basic Panel 
 
    </div> 
 
    </div> 
 
</div>

+1

不错,我忘了'vw'! – Pete

+0

@Keith其实这是一个非常好的主意:) ty – BurebistaRuler

+1

没有probs。侥幸的位是20px,我可以理解它是10px,但考虑到它,我认为身体有一个默认的10px的边距,所以这可能是额外的10px来自...因此,'body-margin + body-填充+容器填充= 10px + 10px + 15px'。最终='-50%-35px' – Keith

1

如果我没有理解问题...

您需要定义左边距和利润率上到所有家长的负和值offsetLeft和机顶盒简单了如果所有父母都将位置转换为负数和。

function getOffsetLeft(elem) 
{ 
    var offsetLeft = 0; 
    do { 
     if (!isNaN(elem.offsetLeft)) 
     { 
      offsetLeft += elem.offsetLeft; 
     } 
    } while(elem = elem.offsetParent); 
    return offsetLeft; 
} 

我找到了一些答案您:

finding element's position relative to the document

现在你知道你的立场,这是很容易设置的元素位置类型绝对新的位置。

你想要某种全屏。将x位置设置为 - (sumOfOffsetLeft) 也适用于y。

对于宽度100%,不需要计算,只需使用window.innerWidth也许是 window.innerWidth/100 * 95(屏幕的95%)。

相关问题