CSS 位置绝对/相对更改外部 div 对齐方式

标签 css html css-position

有人能解释一下为什么红色 div 容器(“标签”)在底部对齐,绝对位置作为内部容器,如果相对位置在顶部。 为什么会影响内部 div 容器和外部 div 容器?

<div>
  <div style="position: relative; display:inline-block; height:auto; background: red">Label</div>
  <div style="position: relative; display:inline-block; height:100px; width:100px; background: blue">
  <div style="position: absolute; height: 20px; width: 20px">XXXX</div>
</div>

With inner div position absolute

<div>
   <div style="position: relative; display:inline-block; height:auto; background: red">
      Label
   </div>
   <div style="position: relative; display:inline-block; height:100px; width:100px; background: blue">
      <div style="position: relative; height: 20px; width: 20px">XXXX</div>
   </div>

With inner div position relative

最佳答案

原因是,display: inline-block元素被视为位于一行(如文本),默认情况下它们的文本内容(更准确地说:他们文本的最后 ,至少只要它还在容器内)在底部对齐。

当您将第三个 DIV 的 position 更改为 absolute 时,它的文本将独立于父 DIV,而是将 block 本身放在父 DIV 的左上角分区。由于现在第二个DIV中没有直接的“真实文本”,所以第二个DIV的底部与第一个DIV的文本(英文表达不确定)的基线对齐。

关于CSS 位置绝对/相对更改外部 div 对齐方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34269749/

相关文章:

html - 如何对齐侧边栏中的图标

javascript - VUE : Disable buttons until animation ends

html - 允许用户在 Objective C 中创建和查看 HTML 文件?

html - 我怎样才能使这个模式及其内容响应?

javascript - 如何将div放在表格元素前面

html - 每当调整窗口大小时如何将文本保留在第一张图像后面?

html - 如何在 A4 纸张大小的页面中制作 HTML 页面?

javascript - 放大一个点(使用缩放和平移)

html - 绝对定位元素和响应式设计

html - 为什么垂直居中网页在小型显示器和移动设备上会中断?