【问题标题】:Append element to outside of div将元素附加到 div 之外
【发布时间】:2018-04-07 03:49:28
【问题描述】:

我有 div,它们一个接一个地放置,并且它们需要与每个兄弟姐妹相邻。同时,有一个按钮/选项卡属于该 div,并“焊接”到其父 div 的顶部,如下图所示:

鉴于我的主要目标是让相关 div 的(描边)边框用作兄弟元素之间的边框,我将如何创建这种效果?

【问题讨论】:

  • 使用绝对定位的伪元素。
  • 你的意思是像 .div:before in css?

标签: html css floating


【解决方案1】:

按钮的绝对位置

div{
  width:200px; height:120px;
  border:2px solid red;
  position:relative;
}

.tab{
  position:absolute;
  height:20px; width:50px;
  top:-20px; right:-2px;
  background:red;
  border:2px solid red;
}

div:nth-child(2){
  border-color:blue;
}
div:nth-child(2) .tab{
  background:blue;
  border-color:blue;
}

/*just to make space in this snippet*/
div:first-child{
  margin-top:20px;
}
<div>
  <button class="tab"/>
</div>
<div>
  <button class="tab"/>
</div>

【讨论】:

  • 您如何将元素放置在您创建的选项卡中顺便说一句
  • 在我的情况下,一个按钮将在那里结束
  • @Skyler 然后使用相同的技术,仅定位元素而不是伪元素。我已经更改了我的示例,请回来查看。
【解决方案2】:

要将元素添加到 div 之外,可以使用 jQuery。

你可以试试这个例子

<style>
  .bg-green {
    width: 100px;
    height:100px;
    background: #0f0;
    margin: 10px;
  }
</style>
<button onclick="appendElement()">Click To Appent to Outside The Element</button><br><br>
<div id="example" class="bg-green"></div>

<script>
 function appendElement(){
   $('#example').after('<div class="bg-green"></div>')
 }
</script>

希望对你有帮助

【讨论】:

    【解决方案3】:

    您可以为图片中的蓝色 div 使用 z-index,它的值大于红色边框框,并将其定位为与红色 div 框元素重叠。例如对于您的蓝色 div 填充框:

    .blue-filled-div {
        position: absolute;
        left: 100px; // replace the values according to red box
        top: 150px;
        z-index: 10;
    }
    

    z-index 将为您的蓝色 div 赋予“深度”并将其放置在红色框 div 的前面。

    【讨论】:

    • 无论如何,蓝色框都会在红色框的前面/上方,因为它稍后会出现在 html 结构中。无需 z-index。
    猜你喜欢
    • 2014-02-14
    • 2015-01-23
    • 2021-04-18
    • 2015-10-02
    • 2020-09-02
    • 2021-06-29
    • 1970-01-01
    • 2016-03-26
    • 2012-08-30
    相关资源
    最近更新 更多