我有一个 div
包含两个 label
元素。每个 label
都应该位于 div
的一侧。由于标签是行内元素,我尝试使用 display: block
和 display: inline-block
让边距生效,但结果不是预期的。
div {
color: #ffffff;
background-color: #3f3f3f;
}
label:nth-of-type(1) {
margin-left: 5px;
}
label:nth-of-type(2) {
display: block;
<!-- display: inline-block; -->
margin-right: 5px;
margin-left: auto;
}
<div>
<label>Left side label</label>
<label>right side label</label>
</div>
正如您在代码执行中看到的那样,第二个标签不考虑边距,而是显示在第一个标签的下方。
最佳答案
标签必须有宽度和 display:block 才能使用 margin auto。
今天使用 flexbox 更灵活。
div {
color: #ffffff;
background-color: #3f3f3f;
display:flex;
flex-flow: row nowrap;
justify-content: space-between;
}
label:nth-of-type(1) {
margin-left: 5px;
}
label:nth-of-type(2) {
margin-right: 5px;
}
<html>
<body>
<div>
<label>Left side label</label>
<label>right side label</label>
</div>
</body>
</html>
关于html - 尽管使用显示 block ,但 margin 自动不被尊重,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54241422/