如何使图像适合css中的按钮?

时间:2014-04-10 23:40:20

标签: html css

我在我的网站上创建了两个按钮,当我将鼠标悬停在图像上时,我打算将它们转换为图像。我遇到的问题是,在悬停后,图像不太适合框内(它太大了)。我如何调整它以使其在悬停在盒子上时适当地放入盒子内?

这是HTML:

<a href="link.html">
<div class="main-button">
<h2 class="main-text">Maintenance</h2>  
</div></a>


<a href="link2.html">
<div class="docs-button">   
<h4 class="docs-text">Other Documents</h4>  
</div></a>

和CSS:

.main-button {
width: 230px;
height: 230px;
border: 5px solid white;
overflow: hidden;
background: #0099DF;
margin-left:100px;
float:left;
}

.main-text {
font-size: 24px;
color:#FFFFFF;
top: 110px;
height: 80px;
width: 170px;
margin-left:40px;
margin-top:150px;
}

.docs-button {
width: 230px;
height: 230px;
border: 5px solid white;
overflow: hidden;
background: #545454;
margin-right:100px;
position:fixed; 
right:30%;
float:center;
}

.docs-text {
font-size: 24px;
color:#FFFFFF;
top: 110px;
height: 80px;
width: 170px;
margin-left:60px;
margin-top:120px;
}

.main-button:hover {
background-image:url('../images/settings.png');


}

.docs-button:hover {
background-image:url('../images/documents.png');
}

3 个答案:

答案 0 :(得分:0)

尝试background-size:cover - 例如

.main-button:hover {
    background-image:url('http://placekitten.com/200/300');
    background-size:cover;
}

.docs-button:hover {
    background-image:url('http://placekitten.com/g/200/300');
    background-size:cover;
}

答案 1 :(得分:0)

background-size:如果要查看所有图像,则包含,或100%100%采用100%宽度和100%高度,但在这种情况下,您的图像可能是shell

答案 2 :(得分:0)

你好TheOrangeRemix

对于您的问题,我有一个可行的解决方案。我的第一步是查看图像的属性并获取尺寸,例如100x100255x100

在这里,您需要将该比例转换为百分比。这是我在计算比率百分比时经常使用的工具:Ratio to Percentage Calculator

一旦您确定了百分比(我将使用1:2,即50%)。您想要创建一个锚标记(<a>)并为其提供一些样式:

注意:这可能有点过分设计,但确实可以满足您的要求。)

html, body {
  width: 100%;
  height: 100%;
  background: #000;
  margin: 0;
}

.wrapper {
  height: 100%;
  width: 100%;
  max-width: 400px;
  margin: 0 auto;
  background: #fff;
}

.mainButton {
  display: inline-block;
  padding-top: 50%;
  width: 100%;
  background: url('https://via.placeholder.com/100x50');
  background-size: 100% 100%;
  position: relative;
}

.mainButton .text {
  font-size: 22px;
  color: #000;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
<div class="wrapper">
  <a href="/somewhere/something" class="mainButton">
    <span class="text">
        Hello, I am a button.
    </span>
  </a>
</div>