Angular编码器可能会将此代码识别为已修改的Tour of Heroes项目。如何设置"徽章的宽度" CSS类是动态的,ul
中的所有徽章都是相同的宽度,适合最长的id?因此,徽章宽度属性应为2ch,其中给定的虚拟数据当前最大长度为2。
模板
<ul class="contacts">
<li *ngFor="let contact of contacts">
<a routerLink="/detail/{{contact.id}}">
<span class="badge">{{contact.id}}</span>{{contact.name}}
</a>
<button title="Delete contact" (click)="delete(contact)">x</button>
</li>
</ul>
CSS
.contacts .badge {
color: white;
background-color: #607D8B;
justify-content: flex-end;
width: 2ch;
padding: 0 1ch 0 1ch;
}
虚拟数据
const contacts = [
{ id: 1, name: 'John McClane' },
{ id: 2, name: 'Holly Gennero' },
{ id: 3, name: 'Harry Ellis' },
{ id: 4, name: 'Karl Vreski' },
{ id: 5, name: 'Al Powell' },
{ id: 6, name: 'Tony Vreski' },
{ id: 7, name: 'Theo' },
{ id: 8, name: 'Agent Johnson' },
{ id: 9, name: 'Special Agent Johnson' },
{ id: 10, name: 'Dwayne T. Robinson' },
{ id: 11, name: 'Yoshinobu Takagi' },
{ id: 12, name: 'Hans Gruber'}
];
我已尝试根据此SO answer设置页面样式但没有运气。如果可能的话,我更喜欢在CSS中保留样式,而不是在javascript中以编程方式设置宽度。
答案 0 :(得分:0)
您可以设置span
的宽度并在锚标记中使用display:flex
Stack Snippet
.contacts .badge {
color: white;
background-color: #607D8B;
width: 24px;
text-align: center;
padding: 0 1ch 0 1ch;
}
.contacts li {
margin-bottom: 10px;
display: flex;
}
.contacts li a {
display: flex;
}
&#13;
<ul class="contacts">
<li>
<a>
<span class="badge">1</span>John McClane
</a>
<button title="Delete contact" (click)="delete(contact)">x</button>
</li>
<li>
<a>
<span class="badge">9</span>Special Agent Johnson
</a>
<button title="Delete contact" (click)="delete(contact)">x</button>
</li>
<li>
<a>
<span class="badge">11</span>Yoshinobu Takagi
</a>
<button title="Delete contact" (click)="delete(contact)">x</button>
</li>
</ul>
&#13;
答案 1 :(得分:0)
如果您能够稍微更改HTML结构,可以使用以下表格:
.contacts {
display: table;
}
.contacts li {
display: table-row;
}
.contacts li span,
.contacts li a,
.contacts li button {
display: table-cell;
}
.contacts .badge {
color: white;
background-color: #607D8B;
padding: 0 1ch 0 1ch;
text-align:right;
}
<ul class="contacts">
<li>
<span class="badge">1</span>
<a>
John McClane
</a>
<button title="Delete contact">x</button>
</li>
<li>
<span class="badge">9</span>
<a>
Special Agent Johnson
</a>
<button title="Delete contact">x</button>
</li>
<li>
<span class="badge">1001</span>
<a>
Yoshinobu Takagi
</a>
<button title="Delete contact">x</button>
</li>
</ul>