0

我有一个我必须div在其中放置一个图标和一些文本到它的右侧,并安排整个事物,使它们都保持居中对齐(图像和文本之间有一个小间隙)。问题是,文本长度可能会有所不同。因此,如果是像Liberia这样的短文本,整个元素会靠近中心挤在一起,而如果是像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;
}

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

4

3 回答 3

2

首先,正如 JoostS 所说,去掉你float:left的 s 然后,你会得到一个未对齐的文本字符串。要解决此问题,请去掉top:5px;.location_text 的顶部并添加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>

于 2016-05-31T21:20:13.830 回答
1

我更新了它https://jsfiddle.net/d8t9e0p6/4/

您必须将 text-align center 放在容器上,并且 imagetext 容器需要自动宽度并显示内联块;

.container {
  width: 260px;
  height: 298px;
  background: yellow;
  text-align:center;
}

.imagetext {
  width:auto;
  height: 20px;
  background: green;
  position: relative;
  top: 50px;
  text-align: center;
  display:inline-block;
}
于 2016-05-31T21:13:23.447 回答
1

删除float:leftcss 语句。

于 2016-05-31T21:14:01.533 回答