我一直在努力解决一个永恒的问题:垂直对齐。
目前我已经使用了许多技巧作为display: table-cell;
或惊人的flex
,但这次我找不到合适的解决方案:
我有一个容器div
有两个孩子,一个是div
,background-image
,另一个包含h2
标题和{ {1}}带有可变大小文字。
垂直对齐 p
,而无需为图像容器指定除{x}}以外的background-image
。< / p>
background-size
CSS
min-height
这里有一个jsfiddle来看它的实际效果。我已经阅读了很多与这个问题有关的问题,很久以前也读过它们,但是没有找到关于这个的问题。
提前,谢谢!
通过<div class="wrapper">
<div class="image"></div>
<div class="text">
<h2>Title</h2>
<p>
Variable length text
</p>
</div>
</div>
添加.wrapper{
width : 100%;
}
.wrapper div{
display: inline-block;
}
.image{
width: 20%;
background-image: url('path/to/img.jpg');
background-size: contain;
background-position: center;
background-repeat: no-repeat;
min-height:100px; // Not displaying without
}
.text{
width: 60%;
}
显示flex
显示的方法:
.wrapper
但它仍然使用display: flex;
justify-content: center;
align-items: center;
来显示min-height
,我希望它有background-image
updated jsfiddle
答案 0 :(得分:0)
我不确定Vertically align
你的意思
你想把图像放在文本上面吗?
如果是这样,你需要删除该显示:.wrapper div中的inline-block
如果你想把图像放在文本的背景中,
你应该使用position:absolute到图像类..
并增加z-index
,
或者只是将你的背景放在文本课......
答案 1 :(得分:0)
对于2 inline-block
并排,vertical-align
将需要重置。 (defaut是baseline
)
您需要重置为vertical-align:middle;
答案 2 :(得分:0)
您可以使用 CSS表格
执行此操作
.wrapper {
display: table;
}
.image{
width: 20%;
display: table-cell;
background: url('https://images.duckduckgo.com/iu/?u=http%3A%2F%2Ftse1.mm.bing.net%2Fth%3Fid%3DOIP.M3e54c25b2796b134bf010adb75160216H0%26pid%3D15.1&f=1');
background-repeat: no-repeat;
background-size: contain;
background-position: center;
vertical-align: middle;
}
.text{
width: 60%;
display: table-cell;
vertical-align: middle;
}
&#13;
<div class="wrapper">
<div class="image"></div>
<div class="text">
"But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?"
</div>
</div>
&#13;