我想知道,我有一个像这样的按钮:
<button><i class="font-icon-class"></i></button>
如果按钮还应该包含文本或其他HTML标签,我是否可以向.font-icon-class
添加填充(或其他样式)?因此,如果我的按钮是这样的:
<button><i class="font-icon-class"></i> Button Text </button>
或
<button><i class="font-icon-class"></i> <img src="..."></button>
我认为我可以使用CSS选择器来应用padding-right
,例如
.font-icon-class + * {
padding-right: 5px;
}
显然那是行不通的,我知道我可以使用JavaScript,但我想知道CSS是否可以提供解决方案?
非常感谢。
答案 0 :(得分:5)
您可以尝试:only-child选择器
.font-icon-class:only-child {
padding-right: 0px;
}
.font-icon-class {
width: 15px;
background: lime;
padding-right: 15px;
}
button {
width: 150px
}
<button><i class="font-icon-class">test</i></button>
<button><i class="font-icon-class">test</i><span>HELLO</span></button>
答案 1 :(得分:0)
button {
padding: 2%;
}
<button><i class="font-icon-class"></i> Button Text </button>
答案 2 :(得分:0)
CSS是级联样式表的缩写,这意味着它随着代码的向下而不是向上添加样式。因此,您不能(还好吗?我相信我会读到将来可以在某个地方使用的样式),如果一个元素后面有另一个元素,则可以添加样式。
一种解决方案-如果您可以访问HTML,则可以在.font-icon-class
之后的元素周围添加一个跨距,就像这样:
<button>
<i class="font-icon-class"></i>
</button>
<button>
<i class="font-icon-class"></i>
<span>Button Text</span>
</button>
<button>
<i class="font-icon-class"></i>
<span><img src="..."></span>
</button>
然后您自己的CSS将起作用,但是您可以缩小它的范围,以免在.font-icon-class
之后不定位所有元素,将填充更改为左侧,并将范围显示为inline-block:>
.font-icon-class + span {
display: inline-block;
padding-left: 5px;
}
如果在.font-icon-class
元素之后,则会在按钮内的span元素中添加填充
答案 3 :(得分:0)
如果不需要的话,不需要任何HTML标记或文本。
从您的问题中我理解的是,您可以像这样直接对类进行样式设置,
如果要在按钮中的下一个元素上添加填充或任何样式,则可以执行此操作。
.font-icon-class + *{ any Style of your choice }
.font-icon-class {
padding-right: 15px;
}
<button><i class="font-icon-class"></i></button>