我正在尝试在按钮内添加图像,并希望将其中心对齐,因为我已将背景位置作为中心,但是它仍在正确对齐。谁能建议我如何将其对准中心?
demo.html
<html lang="en">
<head>
<link rel="stylesheet" href="demo.css">
<title>Document</title>
</head>
<body>
<button class="closeIconRegion"> <span class="closeIconStyle"> </span></button>
</body>
</html>
demo.css
.closeIconRegion {
position: relative;
overflow: hidden;
width: 30px;
height: 30px;
background: Orange;
}
.closeIconStyle {
cursor: pointer;
display: block;
height: 25px !important;
width: 25px !important;
background-position: left;
background-image: url(/images/closebtn_white.png);
float: left;
}
输出::
答案 0 :(得分:1)
如果您知道图像/按钮的高度和宽度,则可以在按钮本身中使用background-position: center
,这样可以解决您的情况。
.close-icon {
width: 60px;
height: 60px;
background: Orange;
background-image: url(https://via.placeholder.com/60);
background-position: center;
}
<button class="close-icon"></button>
如果您不知道图像/按钮的大小,那么我建议使用flexbox,并使其居中对齐。
答案 1 :(得分:0)
尝试一下:
.closeIconRegion {
position: relative;
overflow: hidden;
width: 30px;
height: 30px;
background: Orange;
padding: 0;
display: flex;
align-items: center;
justify-content: center;
}
.closeIconStyle {
cursor: pointer;
display: block;
height: 25px !important;
width: 25px !important;
background-position: center;
background-image: url(/images/closebtn_white.png);
}
答案 2 :(得分:0)
如果按钮的尺寸与图像的尺寸不同,则应将background-size: cover
设置为样式规则:
button{
background-image: url(https://placekitten.com/408/287);
background-position: center;
background-size: cover;
height: 239px;
width: 500px;
}
<button></button>