在 CSS 中的图像中定位按钮
Positioning a button within an image in CSS
我想使用 CSS 在图像中插入一个按钮;图像具有固定的宽度和高度,位于页面中央。
按钮必须在不同分辨率的图像中保持静止。
在你的 CSS:
myImage {
background-image:url('image.jpg');
background-size:cover;
}
一定要给你的按钮一个 ID
在你的 HTML
<button id='myImage' type='submit'> </button>
要将按钮放在您想要的位置,只需给它一些边距即可:
.wrapper button {
margin-left:81%; margin-top:3%;
}
但我相信您希望带有背景图像的 div 永远不会大于 window,对吗?在这种情况下,您将需要更多 CSS:在 div 上设置最大宽度和最大高度,然后您还需要将 html 和正文设置为固定的宽度和高度,否则 max-width 和 max-height 将不知道它们应该相对于什么。
所以,那是
html, body {width:100%; height:100%; margin:0; padding:0;}
.wrapper {
(..)
margin:0 auto;
max-width:100%; max-height:100%;
}
CSS 不允许 <img>
标签内有其他元素。在这种情况下,我通常的做法是将图像和按钮都放在两个包装器 <div>
元素中,这些元素的作用类似于 table(垂直和水平居中)。 像这样;
HTML
<div class="wrapper">
<div>
<img src="[your image src]">
<a class="button" href="[go to page]">Button</a>
</div>
</div>
CSS
.wrapper{
display: table;
width: 100%; /* Add or remove this depending on your layout */
}
.wrapper > div{
display: table-cell;
vertical-align: middle;
text-align: center;
}
只要图像没有大小限制,它就应该齐平地位于图像的中心 :)。享受吧!
编辑 ---
或者,删除 <img>
标签并将其作为 .wrapper
的背景图像并使用 background-size: cover;将它居中 :)。然后你就可以轻松控制图片的高度和宽度了。
记得也要使用供应商前缀。尽管它们在 Sass.
中,但我有一个方便的列表 here
我想使用 CSS 在图像中插入一个按钮;图像具有固定的宽度和高度,位于页面中央。 按钮必须在不同分辨率的图像中保持静止。
在你的 CSS:
myImage {
background-image:url('image.jpg');
background-size:cover;
}
一定要给你的按钮一个 ID
在你的 HTML
<button id='myImage' type='submit'> </button>
要将按钮放在您想要的位置,只需给它一些边距即可:
.wrapper button {
margin-left:81%; margin-top:3%;
}
但我相信您希望带有背景图像的 div 永远不会大于 window,对吗?在这种情况下,您将需要更多 CSS:在 div 上设置最大宽度和最大高度,然后您还需要将 html 和正文设置为固定的宽度和高度,否则 max-width 和 max-height 将不知道它们应该相对于什么。
所以,那是
html, body {width:100%; height:100%; margin:0; padding:0;}
.wrapper {
(..)
margin:0 auto;
max-width:100%; max-height:100%;
}
CSS 不允许 <img>
标签内有其他元素。在这种情况下,我通常的做法是将图像和按钮都放在两个包装器 <div>
元素中,这些元素的作用类似于 table(垂直和水平居中)。 像这样;
HTML
<div class="wrapper">
<div>
<img src="[your image src]">
<a class="button" href="[go to page]">Button</a>
</div>
</div>
CSS
.wrapper{
display: table;
width: 100%; /* Add or remove this depending on your layout */
}
.wrapper > div{
display: table-cell;
vertical-align: middle;
text-align: center;
}
只要图像没有大小限制,它就应该齐平地位于图像的中心 :)。享受吧!
编辑 ---
或者,删除 <img>
标签并将其作为 .wrapper
的背景图像并使用 background-size: cover;将它居中 :)。然后你就可以轻松控制图片的高度和宽度了。
记得也要使用供应商前缀。尽管它们在 Sass.
中,但我有一个方便的列表 here