【问题标题】:CSS Center Button Image In Div [duplicate]div中的CSS中心按钮图像[重复]
【发布时间】:2020-09-24 18:23:21
【问题描述】:

我想要一个按钮图像在水平和垂直大小固定的 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 中而不是在整个页面中?

【问题讨论】:

  • 先试试position:relative

标签: html css center


【解决方案1】:

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

justify-content: center 和 align-items: center

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

如果您想了解更多信息,请查看此网站:https://css-tricks.com/snippets/css/a-guide-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>

【讨论】:

  • 如果这解决了你的问题,请接受这个作为正确答案:),这样其他人就可以看到你的问题已经解决了
  • 这很有效,也是我在元素居中时采用的解决方案。如果您在一个容器中添加多个元素,请确保将“ flex-direction: column; ”添加到容器中。这会将嵌套元素堆叠在彼此下方。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-04-07
  • 1970-01-01
  • 2020-07-20
  • 2021-12-08
  • 1970-01-01
  • 2019-03-25
  • 2018-01-19
相关资源
最近更新 更多