在样式组件中的图像上添加文本
Adding text over an image in styled components
我有一个如下所示的购物车图标:
这是我使用以下代码引用的 SVG 图像:
<Nav.Link as={Link} to="/cart" className="pr-0">
<Image src={cartIcon} className="nav-icon"></Image>
</Nav.Link>
我正在实施动态添加到购物车功能,这需要在图标上添加添加到购物车的产品数量。该图标应该大致如下图所示:
这是我目前尝试过的方法:
<Nav.Link as={Link} to="/cart" className="pr-0">
<Image src={cartIcon} className="nav-icon"></Image>
<Count> {0}</Count>
</Nav.Link>
const Count = styled.span`
-moz-border-radius: 20px;
border-radius: 20px;
border: solid black;
background-color:lightgrey;
color:black;
padding-left:3px;
padding-right:7px;
padding-top:3px;
padding-bottom:3px;
font-size:1.1em;
`;
这是我得到的输出:
考虑到它是一个 SVG 文件,是否可以将此 Span 放在购物车图标的顶部?
首先,我创建了父级,其相对位置如下,围绕着图像和数字:
<div style={{ position: "relative", width: "fit-content" }}>
<img
alt="Girl in a jacket"
style={{ height: "80px", width: 80 }}
src="https://picsum.photos/200/300"
/>
<div className="number">1</div>
</div>
请记住,父图像和图像的宽度应相同。
然后我将这些 css 属性添加到您上面写的图像 css 中,以便将其放置在图像的右上角:
.number {
//placing at top right corner of the parent
position: absolute;
top: 0px;
right: 0px;
//move the number for 50% of its width and height to the top right corner, to
//achieve better visual results
transform: translate(50%, -50%);
//other parts of your css :)
-moz-border-radius: 20px;
border-radius: 20px;
border: solid black;
background-color: lightgrey;
color: black;
padding-left: 3px;
padding-right: 7px;
padding-top: 3px;
padding-bottom: 3px;
font-size: 1.1em;
}
我有一个如下所示的购物车图标:
这是我使用以下代码引用的 SVG 图像:
<Nav.Link as={Link} to="/cart" className="pr-0">
<Image src={cartIcon} className="nav-icon"></Image>
</Nav.Link>
我正在实施动态添加到购物车功能,这需要在图标上添加添加到购物车的产品数量。该图标应该大致如下图所示:
这是我目前尝试过的方法:
<Nav.Link as={Link} to="/cart" className="pr-0">
<Image src={cartIcon} className="nav-icon"></Image>
<Count> {0}</Count>
</Nav.Link>
const Count = styled.span`
-moz-border-radius: 20px;
border-radius: 20px;
border: solid black;
background-color:lightgrey;
color:black;
padding-left:3px;
padding-right:7px;
padding-top:3px;
padding-bottom:3px;
font-size:1.1em;
`;
这是我得到的输出:
首先,我创建了父级,其相对位置如下,围绕着图像和数字:
<div style={{ position: "relative", width: "fit-content" }}>
<img
alt="Girl in a jacket"
style={{ height: "80px", width: 80 }}
src="https://picsum.photos/200/300"
/>
<div className="number">1</div>
</div>
请记住,父图像和图像的宽度应相同。
然后我将这些 css 属性添加到您上面写的图像 css 中,以便将其放置在图像的右上角:
.number {
//placing at top right corner of the parent
position: absolute;
top: 0px;
right: 0px;
//move the number for 50% of its width and height to the top right corner, to
//achieve better visual results
transform: translate(50%, -50%);
//other parts of your css :)
-moz-border-radius: 20px;
border-radius: 20px;
border: solid black;
background-color: lightgrey;
color: black;
padding-left: 3px;
padding-right: 7px;
padding-top: 3px;
padding-bottom: 3px;
font-size: 1.1em;
}