Ary*_*rya 0 html css centering flexbox
我有一个这样的 div,我希望文本和图像水平对齐,其中 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>问题是“窗口”可以是任意大小,图像可以是相当数量的大小,文本内容中的项目可以更长和更大的字体大小。此外,文本的第二行并不总是可见的。
这是一个问题,因为如果文本很长,那么 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 规则中的宽度 % 变大来解决这个问题,但是对于大窗口中的小内容,它将不再居中。
长话短说,有没有更好的方法可以让不同大小的文本居中,而不必让它很窄?
谢谢!
要在 div 内水平对齐文本和图像,您可以使用display:flex和justify-content: center。Justify-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>希望这可以帮助!