简体   繁体   English

如何添加一个忽略Javascript中父级的左边缘和填充的子元素

[英]How to add a child element that ignores the left marging and padding of the parent in Javascript

Please take a look at this jsfiddle: 请看看这个jsfiddle:

http://jsfiddle.net/dd4g4re5/ http://jsfiddle.net/dd4g4re5/

This is the code: 这是代码:

HTML HTML

<div class="a"></div>

CSS CSS

div{
    width: 200px;
    height: 200px;
    background: red;
}

.a {
    padding-left: 6px;
}
.b {
    position: relative;
    background: blue;
}

JAVASCRIPT JAVASCRIPT

var divA = document.getElementsByTagName("div")[0];
var divB = document.createElement("div");
divB.className="b";

divA.appendChild(divB);

I want to position the child div in top of the container div, so it completely overlap the parent. 我想将子div放在容器div的顶部,因此它与父级完全重叠。 But as you can see, that is not possible because of the left padding of the parent. 但正如您所看到的那样,由于父级的左侧填充,这是不可能的。

I guess I could do something like this: 我想我可以这样做:

divB.style.left = -(divA.leftPadding + divA.leftMargin)+"px";

But I hope there is a batter way to do that, like some native function in Javascript, so I don't have to make that kind of calculations. 但是我希望有一种更好的方法可以做到这一点,就像Javascript中的一些本机函数一样,所以我不必进行那种计算。

Also, I would like to avoid setting the child an absolute position. 另外,我想避免让孩子处于绝对位置。

Using border-box here will make sure they both fit the desired widths. 在这里使用border-box将确保它们都符合所需的宽度。 And you'll want to give the child element a negative left margin the same value as it's parent left padding. 并且你想要给子元素一个负左边距和它的父左边距相同的值。

 var divA = document.getElementsByTagName("div")[0]; var divB = document.createElement("div"); divB.className="b"; divA.appendChild(divB); 
 div{ width: 200px; height: 200px; background: red; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; } .a { padding-left: 6px; } .b { position: relative; background: blue; margin-left: -6px; } 
 <div class="a"></div> 

You could position the child absolutely within the (relative) parent, like so: 您可以将孩子完全放在(相对)父级中,如下所示:

.parent {
    position: relative;
    padding: 10px;
}
.child {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
}

http://jsfiddle.net/bvaughn/ouxsdmfc/ http://jsfiddle.net/bvaughn/ouxsdmfc/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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