html - CSS 相对-绝对位置

标签 html css

我是网页设计新手,想了解 CSS 中定位的概念。我对相对和绝对定位元素有一些了解。在下面的 fiddle 中,我有一个 <div>作为 <p> 的父级.当我做 p position:absolute ,边框崩溃不像我制作 <span> 时那样position:absolute ,它的行为符合预期(我能够移动带有边框的元素中的单词)。请指出我看错了什么?为什么边界仅在 <p> 的情况下崩溃绝对定位

div {
  position: relative;
  border: 2px solid black;
  padding: 10px;
}

p {
  position: absolute;
  top: 10px;
}

span {
  top: 10px;
}
<div>
  <span>possessions</span>
  <p>
    Five suspected gang members attacked two agents who were escorting them in a lift, the Investigative Committee said. The group was handcuffed and it was not immediately clear how they managed to free themselves to attack the guards. The two other suspects
    and three security officers were wounded. The suspects were accused of being part of a group known as GTA Gang, named after the violent game series Grand Theft Auto. The group of Central Asian nationals was suspected of killing 17 motorists in the
    Moscow area between 2012 and 2014. Cars were forced to stop on a main road and their drivers were killed for reasons as yet unknown; none of their were stolen.
  </p>
</div>

最佳答案

When set to absolute or fixed, the element is removed completely from the normal flow of the document.

因此,当您为 p 元素定义 position:absolute 时,它会从文档的正常流中移除,并且边框会崩溃。但是当你没有为 p 定义位置时,它会获得默认位置(静态位置)并保持在文档流中并且边框不会崩溃。

您可以在 p 中使用 relative 而不是 absolute

div{
  position:relative;
  border:2px solid black;
  padding:10px;
  
  }
  
  p {
   position:relative;
   top:10px;
  }
  
  span{
   position:absolute;
   top:10px;
  }
<div >
<span>possessions</span>
<p>
Five suspected gang members attacked two agents who were escorting them in a lift, the Investigative Committee said.
The group was handcuffed and it was not immediately clear how they managed to free themselves to attack the guards.
The two other suspects and three security officers were wounded.
The suspects were accused of being part of a group known as GTA Gang, named after the violent game series Grand Theft Auto.
The group of Central Asian nationals was suspected of killing 17 motorists in the Moscow area between 2012 and 2014. Cars were forced to stop on a main road and their drivers were killed for reasons as yet unknown; none of their  were stolen.
</p>
</div>

关于html - CSS 相对-绝对位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45450298/

相关文章:

javascript - 将类添加到父 div jQuery 的最佳方法是什么

Javascript:创建动态变量和对象名称./html5 localstorage

html - 显示 flex 创造额外的空间 为什么

html - 不要调整背景图片的高度

css - Chrome无法应用过滤器:hue-rotate() and transform:rotate() at the same time in an animation

css - 在未知大小的父容器中居中和间隔图像

html - minmax 行为,灵活的 css 网格

javascript - document.body.scrollHeight 在 firefox/chrome 中产生两种不同的结果

javascript - 将图像缩放到窗口的宽度

html - Flexbox:文本项 `font-size: 0' 并占用空间