gpt4 book ai didi

html - 水平居中对齐文本和图像,其中文本长度可以变化

转载 作者:太空宇宙 更新时间:2023-11-03 21:20:49 37 4
gpt4 key购买 nike

我有一个 div ,我必须在其中放置一个图标和一些文本到它的右边,并安排整个东西,使它们一起保持居中对齐(有一个小图片和文字之间的差距)。问题是,文本长度可能会有所不同。所以如果是像 Libya 这样的短文本,整个元素会挤在中心附近,而如果是像 Bosnia and Herzigovina 这样的大文本,它会散开(虽然仍然居中),图像向左移动。我试过这个:

<div class='container'>
<div class='imagetext'>
<img class='location-icon' src="http://images.clipartpanda.com/blue-location-icon-Location-Icon-Blue.png" />
<span class='location-text'>
Bosnia and Herzigovina
</span>
</div>
</div>

CSS:

.container {
width: 260px;
height: 298px;
background: yellow;
}

.imagetext {
width: 100%;
height: 20px;
background: green;
position: relative;
top: 50px;
text-align: center;
}

.location-icon {
width: 20px;
display: inline-block;
margin-right: 5px;
float: left;
}

.location-text {
font-size: 12px;
display: inline-block;
float: left;
position: relative;
top: 5px;
}

body {
background: white;
font-family: sans-serif;
}

这是 fiddle - https://jsfiddle.net/d8t9e0p6/3/ .即使将 text-align 设置为 center,我也无法将其居中。如何实现正确的居中对齐?

最佳答案

首先,正如 JoostS 所说,摆脱你的 float:left然后,您将得到一个未对齐的文本字符串。要解决此问题,请删除 .location_text 上的 top:5px; 顶部并将 vertical-align:middle 添加到 .location-icon

.container {
width: 260px;
height: 298px;
background: yellow;
}

.imagetext {
width: 100%;
height: 20px;
background: green;
position: relative;
top: 50px;
text-align: center;
}

.location-icon {
vertical-align:middle;
width: 20px;
display: inline-block;
margin-right: 5px;
}

.location-text {
font-size: 12px;
display: inline-block;
position: relative;
}

body {
background: white;
font-family: sans-serif;
}
<div class='container'>
<div class='imagetext'>
<img class='location-icon' src="http://images.clipartpanda.com/blue-location-icon-Location-Icon-Blue.png" />
<span class='location-text'>
Bosnia and Herzigovina
</span>
</div>
</div>

更新添加:

如果使用伪元素,您还可以大大减少标记:

.container {
width: 260px;
height: 298px;
background: yellow;
}

.imagetext {
width: 100%;
height: 20px;
background: green;
position: relative;
top: 50px;
text-align: center;
font-size: 12px;
}

.imagetext::before{
display:inline-block;
content:'';
background-image:url(http://images.clipartpanda.com/blue-location-icon-Location-Icon-Blue.png);
background-size:contain;
width:20px;
height:20px;
background-repeat:no-repeat;
vertical-align:middle;
margin-right:5px;
}

body {
background: white;
font-family: sans-serif;
}
<div class='container'>
<div class='imagetext'>
Bosnia and Herzigovina
</div>
</div>

关于html - 水平居中对齐文本和图像,其中文本长度可以变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37555593/

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