gpt4 book ai didi

html - 并排居中文本和图像

转载 作者:太空宇宙 更新时间:2023-11-04 02:44:57 25 4
gpt4 key购买 nike

我遇到了一个 CSS 问题,我呼吁您提供专业知识来帮助我!

我正在尝试对齐文本和图像。文本和图像应垂直居中、左对齐并紧挨着彼此。这两个元素都应包含在宽度可变的包装 div 中

下面是我到目前为止的代码:

<style>
.cell {
width: 150px;
height: 200px;
box-shadow: 0 0 0.5em #999;
white-space: nowrap;
}

.text_element {
height: 100%;
display: inline-block;
white-space: normal;
float: left;
}

.tooltip_element {
height: 100%;
display: inline-block;
}

</style>

<div class="cell">

<div class="text_element"> This is some random, random text.</div>
<div class="tooltip_element">
<img src="http://www.sainsburysbank.co.uk/library/default/images/life-insurance/icon-tooltip.png"/>
</div>

</div>

当包装内容为 500px 时,上面的代码会生成下一张图片:

enter image description here

在上面的图像中,元素正确地彼此相邻,但没有垂直对齐。

对于宽度200px,我们遇到了另一个问题:

enter image description here

这里我们在文本和图像之间得到了空白,这不应该存在,因为图像应该紧挨着文本。此外,图像元素现在位于 div 之外。

注意:

  • 包装内容可以有不同的宽度

  • 解决方案应适用于所有浏览器(无 flex 解决方案)

  • 不用JS,只能用CSS

非常感谢您的帮助!

编辑:

文本应该左对齐!

最佳答案

好的,这是:

.cell {
width: 210px;
height: 200px;
box-shadow: 0 0 0.5em #999;
white-space: nowrap;
padding-right: 30px;
}
.text_element {
display: inline-block;
white-space: normal;
float: left;
text-align: justify;
position: relative;
}
.tooltip_element {
position: absolute;
left: 100%;
top: 50%;
transform: translateY(-50%);
}
<div class="cell">
<div class="text_element">This is some random, random text. Moar random text. And moar, moar random text...
<div class="tooltip_element">
<img src="http://www.sainsburysbank.co.uk/library/default/images/life-insurance/icon-tooltip.png" />
</div>
</div>
</div>

请注意,我在文本元素中包含了工具提示元素。所以我可以垂直对齐它们。如果他们必须是 sibling ,我需要将他们都包装在一个容器中,以便在没有 flex-box 的情况下垂直居中。

如果您更喜欢 jsFiddle,可以调整单元格宽度,here it is .

关于html - 并排居中文本和图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34018626/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com