CSS垂直和水平对齐事物

时间:2016-03-09 04:48:15

标签: html css

请参阅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;
}

2 个答案:

答案 0 :(得分:0)

您可以使用display:flex执行以下操作。我已在课程ranking上添加,以便将其对齐。

&#13;
&#13;
*{
  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;
}
&#13;
<div class="contentsInfo">
  <img src="http://lorempixel.com/90/30" />
  <span>Here is some info</span>
  <span class="ranking">20</span>
</div>
&#13;
&#13;
&#13;

<强> Fiddle

答案 1 :(得分:0)

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

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