带有图像和文本的水平居中 Flexbox

Horizontally Centering Flexbox with Image and Text

我有一个像这样的 div,我希望文本和图像水平对齐,其中 space 从 div 的左侧和 div 是相等的。这是我当前的代码,尽管它绝对不是最佳的:

.window{
  position:absolute;
  width: 400px;
  height: 300px;
  background-color:#424242;
}
.content{
  padding-top:50px;
  width: 50%;
  position:relative;
  vertical-align: top;
  margin: 0 auto;
  display:flex;
}
img {
  height: 32px;
  width: 32px;
  min-width: 32px;
  min-height: 32px;
  position: relative;
  float: left;
}
.textcontent{
  margin-top: auto;
  margin-bottom: auto;
  margin-left: 16px;
  display: block;
  line-height: 182%;
}
.text{
  font-size: 14px;
}
<!DOCTYPE html>
<html>
<head>
</head>

<body>


<div class="window">
  <div class="content">
    <img src="https://cdn4.iconfinder.com/data/icons/family-and-home-collection/110/Icon__grandfather-32.png" />
    <div class="textcontent">
      <div class="text"> Some Centered Text. </div>
      <div class="text"> Some Other Text. </div>
    </div>
  </div>
</div>

</body>
</html>

问题是“window”可以是任何大小,图像可以是相当大的尺寸,文本内容中的项目可以更长和更大的字体大小。此外,第二行文本并不总是可见。

这是一个问题,因为如果文本很长,50% 的宽度就很小,并且文本在有足够空间的情况下会换行好几次。

.window{
  position:absolute;
  width: 500px;
  height: 300px;
  background-color:#424242;
}
.content{
  padding-top:50px;
  width: 50%;
  position:relative;
  vertical-align: top;
  margin: 0 auto;
  display:flex;
}
img {
  height: 32px;
  width: 32px;
  min-width: 32px;
  min-height: 32px;
  position: relative;
  float: left;
}
.texcontentt{
  margin-top: auto;
  margin-bottom: auto;
  margin-left: 16px;
  display: block;
  line-height: 182%;
}
.text{
  font-size: 14px;
}
<!DOCTYPE html>
<html>
<head>
</head>

<body>


<div class="window">
  <div class="content">
    <img src="https://cdn4.iconfinder.com/data/icons/family-and-home-collection/110/Icon__grandfather-32.png" />
    <div class="textcontent">
      <div class="text"> Some text that is very very long and wraps. </div>
      <div class="text"> This text is also very long and also wraps. </div>
    </div>
  </div>
</div>

</body>
</html>

我可以通过增大 .content 规则中的宽度 % 来解决这个问题,但是对于大 window 中的小内容,它将不再居中。

长话短说,有没有更好的方法让我想要的不同尺寸的文本居中,而不必让它非常窄?

谢谢!

要在 div 内水平对齐文本和图像,您可以使用 display:flexjustify-content: centerJustify-content:center 会将子项对齐到容器的中心。

.content {
  width: 400px;
  display: flex;
  justify-content: center;
  align-items: center; /* Only if you want it vertically center-aligned as well */
  background: #ccc;
  padding: 40px;
}
<div class="window">
  <div class="content">
    <img src="https://cdn4.iconfinder.com/data/icons/family-and-home-collection/110/Icon__grandfather-32.png" />
    <div class="textcontent">
      <div class="text"> Some text that is very very long and wraps. </div>
      <div class="text"> This text is also very long and also wraps. </div>
    </div>
  </div>
</div>

View in CodePen

希望对您有所帮助!