CSS响应式定位内联元素的方法

时间:2018-05-22 14:08:55

标签: html css

我遇到了一个问题,即在破折号周围布局文本,应该在中心,预期会有两个不同的结果。

Html结构:

<div class="wrapper"></div>
   <span class="left">TEXT_ON_THE_LEFT</span>
   <span class="center">&nbsp;-&nbsp;</span>
   <span class="right">TEXT_ON_THE_RIGHT</span
</div>

示例数据:

November 2016 - April 2017
May 2016 - November 2016
January 2016 - May 2016

结果否1:

November 2016   -      April 2017
May 2016        -   November 2016
January 2016    -        May 2016

结果否2:

 November 2016 - April 2017
      May 2016 - November 2016
  January 2016 - May 2016

如何在上面取得两个结果?

最重要的是我们不能指定左右跨距的固定宽度,因为它们包含在父元素(包装器)中,根据屏幕大小RWD设置%宽度(框) -sizing:border-box)

2 个答案:

答案 0 :(得分:1)

简单,创建3个跨度,具有3种不同的对齐方式,具体取决于您的需求

&#13;
&#13;
/* you need to set specific width to the block, so it knows the size of the 
 * block and how much it should align to the side. span's width is auto by 
 * default. Which would on human eye show no difference in text-align */
.lister {
  width: 50px;
  height: 20px;
  display: inline-block;
 }

.left{
  text-align: left;
 }
 
.right {
  text-align: right;
 }
 
.center {
  text-align: center;
 }
&#13;
<span class="lister left">LEFT</span>
<span class="lister center">-</span>
<span class="lister right">RIGHT</span>
&#13;
&#13;
&#13;

要使用特定的结果/外观,只需查找text-align属性即可。 (https://developer.mozilla.org/en-US/docs/Web/CSS/text-align

答案 1 :(得分:0)

事实上,我在描述细节方面并不准确。 感谢您的efford和帮助。 我已经实现了基于flexbox布局的解决方案,如下所示:

&#13;
&#13;
.button{
  width: 300px;
  display: block;
}

.wrapper{
  display: flex;
  align-items: stretch;
}

.wrapper > span{
  display: inline-block;
}

.left{
  text-align: right;
  width: 50%;
  flex-grow: 1;
}

.center{

}

.right{
  text-align: left;
  width: 50%;
  flex-grow: 1;
}
&#13;
<button class="button">
  <div class="wrapper">
     <span class="left">November 2016</span>
     <span class="center">&nbsp;-&nbsp;</span>
     <span class="right">April 2017</span>
  </div>
</button>
<!-- /* some unrelated markup */ -->

<button class="button">
  <div class="wrapper">
     <span class="left">May 2016</span>
     <span class="center">&nbsp;-&nbsp;</span>
     <span class="right">November 2016</span>
  </div>
</button>
<!-- /* some unrelated markup */ -->

<button class="button">
  <div class="wrapper">
     <span class="left">January 2016</span>
     <span class="center">&nbsp;-&nbsp;</span>
     <span class="right">May 2016</span>
  </div>
</button>
<!-- /* some unrelated markup */ -->
&#13;
&#13;
&#13;