简体   繁体   English

如何自动将子div包含到父div中?

[英]How to include child div into parent div automatically?

Is there any way how to add a child div into parent divs.有什么方法可以将子div添加到父div中。 The child div is still same (without changes) but content of parent div is variable.子 div 仍然相同(没有变化)但父 div 的内容是可变的。 Parent div contains child div automatically like CSS div::before but with whole div in it not just text.父 div 像 CSS div::before 一样自动包含子 div,但包含整个 div 而不仅仅是文本。

Basically for each parent automatically generate same child.基本上每个父母都会自动生成相同的孩子。

See figure sample of parent and child divs父子div的图样

How can I make it via CSS ?我怎样才能通过 CSS 制作它? (or JS) (或JS)

It's not completely clear to me what the problem/issue is, but it sounds like you are looking for JS code like this:我并不完全清楚问题/问题是什么,但听起来您正在寻找这样的 JS 代码:

var child = document.createElement('div');
child.innerHTML = '<p>Child!</p>';

var parent = document.createElement('div');
parent.innerHTML = '<p>Parent 1</p>';

parent.appendChild(child);

Not sure I understood your question so I will just give you a solution and then you comment your requirements.不确定我是否理解你的问题,所以我会给你一个解决方案,然后你评论你的要求。

You can have a div that contains another child div which is positioned inside the parent but does not change when you add more content to the parent.您可以拥有一个包含另一个子 div 的 div,该子 div 位于父级内,但在向父级添加更多内容时不会更改。

Here is a fiddle:这是一个小提琴:

http://jsfiddle.net/1fohx3qf/ http://jsfiddle.net/1fohx3qf/

.parent {
border:2px solid black;
padding:5px;
position:relative;
width:124px;
height:120px;
}

.child {
border:2px solid red;
padding:30px;
position:absolute;
bottom:5px;
right:10px;
}

CSS cannot generate content (as such) it can only style it. CSS 不能生成内容(因此),它只能设置样式。

If the element is not present in the HTML nothing will happen.如果该元素不存在于 HTML 中,则不会发生任何事情。

It is possible to add "pseudo content" with a pseudo element but the primary purpose of these pseudo-elements is enhancement not addition of "content" .可以使用伪元素添加“伪内容”,但这些伪元素的主要目的是增强而不是添加“内容” Also they cannot contain HTML.它们也不能包含 HTML。

It would be possible to use a pseudo element with a bg image in this instance as this is essentially styling.在这种情况下,可以使用带有 bg 图像的伪元素,因为这本质上是样式。

JSfiddle Demo JSfiddle 演示

 div { height:250px; width:250px; display: inline-block; margin: 25px; position: relative; /* required */ } div:after { content:""; /* required */ position: absolute; bottom:25px; right:25px; background-image: url(http://www.webdevelopersnotes.com/how-do-i/thumbs/shortcut-arrow.jpg); height:75px; width:75px; background-size:cover; } .one { background: red; width:300px; } .two { background: lightblue; height:300px; }
 <div class="one"></div> <div class="two"></div>

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

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