CSS:如何将div放在彼此之上

时间:2016-12-21 21:29:06

标签: html css

看看这个Fiddle

我正在尝试将div #popup放在页面底部,重叠之前的所有内容和

  • 拥有其父级(#content
  • 的宽度
  • 未给出其父母的宽度

我不确定,但我认为position: absolute在这种情况下不起作用,至少不是我实现它的方式。

我该怎么做?

4 个答案:

答案 0 :(得分:5)

position: absolute用于此类弹出窗口的关键是确保容器设置为position: relative。此外,您需要设置z-index以确保弹出窗口显示在内容上方,并使用top属性设置位置。

要满足弹出窗口宽度的要求,您只需设置width: 100%

#content {
  cursor: pointer;
  position: relative;
}
#popup {
  display: none;
  position: absolute;
  top: 0;
  z-index: 1;
  width: 100%;
}

请在此处查看更新的小提琴:https://jsfiddle.net/xsxo0xmd/18/

从技术上讲,您可以将position: absolute与任何未设置为position : static的容器(位置的默认值)一起使用,如此处所述https://developer.mozilla.org/en-US/docs/Web/CSS/position

  

绝对定位   元素相对于最近定位的祖先定位   (非静态)。如果定位的祖先不存在,则为初始   使用容器。

有关在相对定位中使用绝对定位的说明性指南,请查看https://css-tricks.com/absolute-positioning-inside-relative-positioning/

答案 1 :(得分:1)

将此附加到您的CSS中以获取所述元素:

#popup {
    position: fixed; //this is your friend
    bottom: 0;  //stick to bottom
    z-index: 1; //bring the element in front of other element.
}

我已经为你更新了JSFiddle。

https://jsfiddle.net/xsxo0xmd/15/

答案 2 :(得分:0)

需要绝对位置,因为您希望从父级获取宽度。 由于位置:绝对元素相对于其第一个定位(非静态)祖先元素定位。你也希望弹出这个容器,这将通过z-index实现。

仅供参考,请查看更新的



$(document).ready(function(){
    $('#content').click(
        function(){
            popup = $('#popup');
            if (popup.hasClass('show')) {
                popup.slideUp(250, function() {
                    popup.fadeOut(250).removeClass('show');
                });
            } else {
                popup.slideDown(250, function() {
                    popup.fadeIn(250).addClass('show');
                });
            };
        }
    );
});

    .CodeMirror {
      height: calc(100vh - 25px);
      width: 100%;
    }
    #content {
      cursor: pointer;
      background-color:green;
    }
    #popup {
      display: none;
        position: absolute;
        bottom: 0;
        left: 0;
        width: 100%;
        height: 100px;
        background-color: red;
        z-index: 100;
    }

<script type="text/javascript">
	var myCodeMirror = CodeMirror(document.body, {
  	value: "function myScript(){return 100;}",
    mode:  "javascript",
    lineSeparator: null,
    theme: "default", // theme directory
    indentUnit: 2,
    smartIndent: true,
    tabSize: 2,
    indentWithTabs: false,
    electricChars: true,
    extraKeys: null,
    lineWrapping: false,
    lineNumbers: true,
    firstLineNumber: 1,
    scrollbarStyle: "overlay",
    inputStyle: "contenteditable",
    readOnly: false, // also "nocursor"
    showCursorWhenSelecting: false,
    lineWiseCopyCut: true,
    undoDepth: 200,
    historyEventDelay: 1250,
    autofocus: true
  });
</script>
  
 <div id="content">
   ABC
   <div id="popup">
     DEF
   </div>
 </div>
 
 
 
&#13;
&#13;
&#13;

答案 3 :(得分:0)

尝试在z-index: 2

上使用.popup

#content使用z-index: 1

jsfiddle

Example

相关问题