如何使用 css 的 :before
和/或 after
将图像图标放在按钮的右上角?
最佳答案
:before
和 :after
默认情况下,它们的静态位置基于它们附加到的元素。
查看此代码段。默认情况下,将内容添加到 :after
将显示一些带有单词 Button 的 inline
文本。
将 :after
设置为 display: block
会将其视为一个 block ,因此它位于下方。我已将图像添加到这个新元素的背景中。
现在,如果我们将它的位置设置为 absolute
,并将它移动到右上角,它就会飞到 body 的右上角,因为我们没有相对定位的按钮来锚定我们的绝对
元素。
最后一个按钮设置为 position: relative;
因此 :after
(绝对定位)将锚定到它,因为 :before
和 :after
将它们附加到的元素视为父元素。
button {
padding: 5px 10px;
}
button.text:after {
content: "After";
}
button.img:after {
background: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='15' height='15'><circle cx='7.5' cy='7.5' r='5' /></svg>");
content: "";
width: 15px;
height: 15px;
display: block;
}
button.top-right:after {
position: absolute;
top: 0;
right: 0;
}
button.relative {
position: relative;
}
button.cropper {
overflow: hidden;
}
button.cropper:after {
background: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='40' height='40'><circle cx='20' cy='20' r='15' /></svg>");
width: 40px;
height: 40px;
right: -20px;
}
<button class="text">Button</button>
<button class="img">Button</button>
<button class="img top-right">Button</button>
<button class="img top-right relative">Button</button>
<button class="img top-right relative cropper">Button</button>
关于css - 使用CSS将图标放在按钮的右上角,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49201155/