提问者:小点点

Div中的CSS中心按钮图像[重复]


我想有一个按钮图像中心在一个固定大小的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中居中,而不是在整个页面中?


共1个答案

匿名用户

我使用flexbox样式,将您的代码修改为按钮相对的位置,并且父按钮确保内部的按钮居中

对齐-内容:中心对齐-项目:中心

确保display flex父级的所有子级都在中间水平和垂直对齐。

如果您想了解更多信息,请访问以下网站:https://css-tricks.com/snippets/css/a-guide-to-flexbox/

null

<!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>