一些常见的布局例如图+文案的,有多种方式可以去写,比如padding-left+background或者position+padding-left或者before伪元素。
前两种方法都可以把图片做到绝对的垂直居中,但是它们都是相对整行的容器进行定位的,由于line-height兼容问题的坑,图片实际上不一定会和文字对齐。如果有图文对齐的需求的话,个人建议才用before伪元素来布局,before可以相对文案来定位。
借鉴原作者的写法,发现了另外一个小技巧:利用伪类before和after生成的图片我们很难去让他们与文字一起垂直居中(文字垂直居中相信大家都知道:line-height===height。这里我利用background-size: contain;
/这里把背景图片尺寸设置成contain,不需要考虑图片拉伸的问题/;
height: 44px;等于容器的高度;随后vertical-align: top or bottom都没关系了,因为图片的容器已经和外面的容器在一条线上了。
html:
<ul>
<li class="ent-li">
<p class="left">热门线路sdgdgs水电费广东省分公司的山东干发的</p>
<div class="right">100000000009999999999999999999999999999999999999988</div>
</li>
<li class="ent-li">
<p class="left">热门线路sdgdgs水电费广东省分公司的山东干发的</p>
<div class="right">100000000009999999999999999999999999999999999999988</div>
</li>
<li class="ent-li">
<p class="left">热门线路sdgdgs水电费广东省分公司的山东干发的</p>
<div class="right">100000000009999999999999999999999999999999999999988</div>
</li>
</ul>
css:
body,
p,
ul,
li {
margin: 0;
padding: 0;
}
ul,
li {
list-style: none;
}
/* 图文标题 */
li+li {
border-top: 1px solid #999;
}
p.left {
flex: 1;
text-align: left;
height: 44px;
line-height: 44px;
font-size: 16px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
p.left::before {
content: '';
display: inline-block;
background: url("img/icon.png") center center no-repeat;
background-size: contain;
/*这里把背景图片尺寸设置成contain,不需要考虑图片拉伸的问题*/
width: 28px;
height: 44px;
vertical-align: top;
/*or vertical-align: bottom; 这里因为height和容器的height设成了一致的,所以vertical-align:top或者bottom都无所谓了。*/
margin-right: 5px;
}
/* 左右宽度自适应 */
.ent-li {
margin: 0 45px;
height: 44px;
display: flex;
}
.ent-li::after {
content: '';
background: url('img/arrow.png') center center no-repeat;
background-size: contain;
width: 22px;
height: 44px;
}
.right {
flex: 1;
text-align: right;
line-height: 44px;
font-size: 12px;
color: #999;
padding-left: 10px;
}
图中的布局实际上是分左右两块的,依照ui的需求,文案是要左对齐,数字是要右对齐的。你可能最先想到的是把右侧的数字定位或者浮动到那,左侧的容器加上个margin-right或者padding-right。这样可以实现,但是两侧的文案有极端情况出现。
#####
flex:1;的作用是让这部分的宽度width在外部容器固定的情况下,随意变形,让另外一边的宽度随里面的内容的增大,通俗点将,就是我这边去适应另外一边,那边我不管你怎么变,你变宽我就瘦一点,你瘦了我就可以放我的东西了。#####
看你看中那一边了,如果数字重要,就让文案去自适应,数字有多长就多长,像这边例子的写法;如果注重文案,就让数字去自适应,文案应该也不能太长了,不然数字就没了。。。。