我有一个像这样的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;
}
.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 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规则中的宽度%更大来解决这个问题,但是对于大窗口中的小内容,它将不再居中。
长话短说,有没有更好的方法来获得不同尺寸的文本居中,而不必非常狭窄?
谢谢!
答案 0 :(得分:4)
要在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>
希望这有帮助!