0

アイコンとその右側に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;
}

これはフィドルです - https://jsfiddle.net/d8t9e0p6/3/text-alignに設定しても中央に配置できませんcenter。正しい中央揃えを実現するにはどうすればよいですか?

4

3 に答える 3

2

まず、JoostS が言ったように、s を取り除きfloat:leftます。これを修正する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

float:leftcss ステートメントを削除します。

于 2016-05-31T21:14:01.533 に答える