【问题标题】:CSS Aligning Things Vertically and HorizontallyCSS 垂直和水平对齐事物
【发布时间】:2016-03-09 13:11:13
【问题描述】:

Fiddle

我有一张图片和两组文本(一组是“标签”,一组是“排名”)。

<div class="contentsInfo">
  <img src="http://lorempixel.com/90/30" />
  <span>Here is some info</span>
  <span>20</span>
</div>

我想将每个对齐垂直居中,将标签显示在图像旁边,并使排名数据在容器中右对齐。

但是,它没有在中间对齐,并且正在切换信息和排名“列”(排名显示在中间,标签显示在右侧)。

这是我的 CSS:

.contentsInfo
{
    font-size: 0.80em;
    border-bottom: 1px grey dotted;
    vertical-align: middle;
    display: table;
    width: 100%;
}

.contentsInfo>span
{
    float: right; 
    margin-left: 5px;
    vertical-align: middle;
    display: table-cell;
}

.contentsInfo span
{
    font-size:   1.1em;
}

.contentsInfo img
{
    height: 30px; 
    vertical-align: middle;
    margin-right: 2px 5px 2px 0px;
    padding: 2px 0px;
}

【问题讨论】:

标签: html css


【解决方案1】:

将您的内容包装在元素中并执行以下操作:

HTML:

<div class="contentsInfo">
  <div>
    <img src="http://lorempixel.com/90/30" />
    <span>Here is some info</span>
  </div>

  <div>

    <span>20</span>
  </div>
</div>

CSS:

body,
html {
  padding: 0px;
  margin: 0px;
}

.contentsInfo {
  font-size: 0.80em;
  border-bottom: 1px grey dotted;
  vertical-align: middle;
  display: table;
  width: 100%;
}

.contentsInfo>div {
  margin-left: 5px;
  vertical-align: middle;
  display: table-cell;
}

.contentsInfo > div:first-child {
  width: 100%;
}

.contentsInfo > div:last-child {
  white-space: nowrap;
}

.contentsInfo span {
  font-size: 1.1em;
}

.contentsInfo img {
  height: 30px;
  vertical-align: middle;
  margin-right: 2px 5px 2px 0px;
  padding: 2px 0px;
}

Working Fiddle

【讨论】:

    【解决方案2】:

    您可以使用display:flex 执行以下操作。我已经添加了ranking 类以将其对齐到右侧。

    *{
      margin:0;
    }
    .contentsInfo
    {
        font-size: 0.80em;
        border-bottom: 1px grey dotted;
        display: flex;
        align-items: center;
        
    }
    
    .contentsInfo>span
    {
        margin-left: 5px;
         display: flex;
        flex: 1 1 auto;
        margin-right: 5px;
    }
    
    
    .ranking{
      justify-content: flex-end;
    }
    
    .contentsInfo span
    {
        font-size:   1.1em;
    }
    
    .contentsInfo img
    {
        height: 30px; 
        padding: 2px 0px;
    }
    <div class="contentsInfo">
      <img src="http://lorempixel.com/90/30" />
      <span>Here is some info</span>
      <span class="ranking">20</span>
    </div>

    Fiddle

    【讨论】:

      猜你喜欢
      • 2015-03-15
      • 1970-01-01
      • 2015-02-04
      • 2012-10-10
      • 2015-10-29
      • 2013-11-25
      • 2014-12-05
      • 1970-01-01
      相关资源
      最近更新 更多