包装时CSS文本对齐

时间:2019-03-04 10:13:40

标签: css

调整窗口大小时,例如,我无法对齐文本在移动。 这是HTML:

.count-panel {
  float: left;
  width: 64px;
  border: 1px #888 solid;
}

.count {
  font: 15px/18px Roboto, sans-serif;
  font-size: 42px;
}

.message {
  font-size: 20px;
}

.row {
  clear: both;
  margin-bottom: 16px;
}
<div class='table'>
  <div class='row'>
    <div class='count-panel'>
      <span class='count'>1</span>
    </div>
    <div class='message'>This is line one</div>
  </div>
  <div class='row'>
    <div class='count-panel'>
      <span class='count'>2</span>
    </div>
    <div class='message'>This is line two which is longer than the rest so it can test wrapping</div>
  </div>
  <div class='row'>
    <div class='count-panel'>
      <span class='count'>3</span>
    </div>
    <div class='message'>This is line three</div>
  </div>

较大时:Larger

较小的尺寸:Smaller

我需要第二行中的文本与其他行对齐,而不是像图像中那样用硬线包裹。谢谢。

2 个答案:

答案 0 :(得分:1)

该移动设备上的行为是由于应用于.count-panel元素的浮点数引起的。您可以改为使用flexbox并清理一点CSS代码,如下所示:

  

Codepen demo

.count-panel {
  border: 1px #888 solid;
  flex: 0 0 64px;

}

.count {
  font: 15px/18px Roboto, sans-serif;
  font-size: 42px;
}

.message {
  font-size: 20px;
}

.row {
  margin-bottom: 16px;
  display: flex;
}

答案 1 :(得分:0)

使计数面板不同步的仅仅是您的float: left

我已将您的示例替换为display: flex。我建议在放置元素时避免浮动,因为它从来都不打算用于布局。 Flex是一种更清洁的解决方案,我认为它为您提供了更大的布局选择灵活性。 :-)

我还对HTML布局进行了少许修改,以在数字本身上包括边框,以使它不会在较小的设备上拉伸文本内容的全部大小。

.count {
  font: 42px Roboto, sans-serif;
  min-width: 64px;
  border: 1px #888 solid;
  text-align: center;
  max-height: max-content;
}

.message {
  font-size: 20px;
}

.row {
  display: flex;
  flex-direction: row;
  margin: 0 10px 16px 0;
}
<div class='table'>
  <div class="row">
    <span class="count">1</span>
    <div class="message">This is line one</div>
  </div>
  <div class="row">
    <span class="count">2</span>
    <div class="message">This is line two which is longer than the rest so it can test wrapping</div>
  </div>
  <div class="row">
    <span class="count">3</span>
    <div class="message">This is line three</div>
  </div>
</div>