首页 > 解决方案 > 弹性项目证明内容不能与边距正常工作

问题描述

我在 div 中有 2 个项目。

#picBox {
  width: 800px;
  height: 600px;
  background-color: #8D918D;
  background-image: url('images/IMG_1744.JPG');
  background-repeat: no-repeat;
  background-position: center;
  background-size: contain;
  display: flex;
}

#overlay {
  align-self: flex-end;
  width: 100%;
  height: 20%;
  background-color: black;
  color: white;
  opacity: 0.6;
  margin: 0;
  font-size: 80%;
}

#olText {
  display: flex;
  flex-direction: column;
  justify-content: center;
}

h1,
p {
  margin-left: 10px;
}

h1 {
  margin-top: 10px;
  margin-bottom: 10px;
}

p {
  margin-top: 0;
  margin-bottom: 0;
}
<div id="picBox">
  <div id="overlay">
    <div id="olText">
      <h1>Title</h1>
      <p>Description</p>
    </div>
  </div>
</div>

我需要在#olText 中间垂直对齐的 2 个项目(h1 和 p)。还希望项目距离 div 的左侧 10 px,距离顶部至少 10 px(需要时,因为有很多文本),并且彼此相距 10 px。

现在它接缝了,因为我正在使用边距,所以 flex justify-content 不起作用。这里的解决方案是什么?

标签: htmlcssflexbox

解决方案


您的代码没有问题。h1p在中心垂直对齐。看起来不是这样的原因是因为 的高度与和#olText的总高度相同。您可能需要调整使用高度h1 + margin-topp#olTextmin-height

如果您需要在中心水平对齐它们,请使用 align-items:center;.

#olText {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items:center;
  min-height: 200px;
}

h1,
p {
  margin-left: 10px;
}

h1 {
  margin-top: 10px;
  margin-bottom: 10px;
}

p {
  margin-top: 0;
  margin-bottom: 0;
}
<div id="olText">
  <h1>Title</h1>
  <p>Description</p>
</div>


推荐阅读