html - CSS:为什么 h3 会降低其父 div?

标签 html css

有一个简单的例子,其中 div 元素包含 h3
但是,当 h3 具有相对位置时,h3 元素会从其父元素 div 下拉。
h3 位置更改为绝对位置可以解决此问题。
这是什么原因?

.personal-details{
  background-color: green;
}

.personal-image{
  display: inline-block;
  width: 150px;
  height: 150px;
  background-color: white;
}

.personal-description {
  display: inline-block;
  width: 150px;
  height: 150px;
  background: black;
}


.personal-description h3 {
  position: relative; /*absolute solves the problem*/
}
<div class="personal-details">
    <div class="personal-image"></div>
    <div class="personal-description"><h3 class="name">My Name</h3></div>
</div>

最佳答案

这是由 inline-block 元素的默认 vertical-align: baseline; 属性引起的。

为您的元素使用 vertical-align: top 覆盖默认值将使您到达正确的位置:

.personal-details {
  background-color: green;
  vertical-align: middle
}

.personal-image {
  display: inline-block;
  width: 150px;
  height: 150px;
  background-color: green;
}

.personal-description {
  display: inline-block;
  width: 150px;
  height: 150px;
  background: black;
  vertical-align: top;
}

.personal-description h3 {
  position: relative;
  background: yellow;
}
<div class="personal-details">
    <div class="personal-image"></div>
    <div class="personal-description"><h3 class="name">My Name</h3></div>
</div>

请注意,我说“某处类似正确”,因为元素周围的空间仍然存在问题(请注意黑色方 block 下方的间隙和两个子 div 之间的空间)。但这超出了你的问题范围,已经处理了many times before .

关于html - CSS:为什么 h3 会降低其父 div?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36965540/

相关文章:

css - 带有 twitter bootstrap css 的 XLSTForms

css - 如何避免按钮重叠?

jquery - 为什么这个简单的 jQuery 切换不起作用?

jquery - 用 jquery 旋转然后做其他事情

html - 如何使用双侧边栏设置 html 布局的样式

javascript - 从 javascript 获取 HTML5 WebDB (Web SQL) 数据库的大小

html - Safari 在调整大小时不请求 srcset 图像

css - 如何去掉移动版css中的定位

html - 同一页上的两个无序列表,一个内联和一个初始

php - 初学者 php "Warning: Undefined array key"