我想在一个固定大小的div中设置一个水平和垂直方向的按钮图像。
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
div#fixed-size {
width: 800px;
height: 600px;
border: 1px solid red;
display: block;
}
button {
padding: 0;
margin: auto;
display: block;
width: 256px;
height: 256px;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
</style>
</head>
<body>
<div id="fixed-size">
<button>
<img src="aqua.png">
</button>
</div>
</body>
</html>
我应该写什么来代替 button { /* ... */ }
按钮的中心位置。div
而不是整个页面?
我把你的代码改成了按钮是相对的,而父节点确保里面的按钮居中,使用了flexbox样式。
justify-content: center
和 align-items: center
确保display flex父节点的所有子节点在水平和垂直方向上都在中间对齐。
如果你想了解更多关于它的信息,请查看这个网站。https:/css-tricks.comsnippetscssa-guid-to-flexbox。
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
div#fixed-size {
width: 800px;
height: 600px;
border: 1px solid red;
display: flex;/* changed */
justify-content: center;/* added */
align-items: center;/* added */
}
button {
padding: 0;
margin: auto;
display: block;
width: 256px;
height: 256px;
position: relative;/* changed */
top: 0;
bottom: 0;
left: 0;
right: 0;
}
</style>
</head>
<body>
<div id="fixed-size">
<button>
<img src="aqua.png">
</button>
</div>
</body>
</html>