You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现按钮边框内图片居中?CSS新手技术问询

解决按钮内图片居中的问题

问题分析

你的代码里存在几个关键问题导致图片无法居中:

  • .button 重复设置了 display: inline-block 和 display: block,且未启用flex布局,align-items: center 无法生效
  • padding值存在语法错误:10px 20px` 多了一个多余的反引号
  • 图片默认是inline元素,未设置水平居中样式
  • 多个img使用了同一个id gallery-icon,id作为唯一标识不能重复使用

修复方案

调整按钮为flex垂直布局,修正语法错误,给图片添加居中样式:

修改后的HTML(修正重复id问题)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Protera Survey & Price List</title>
    <link rel="stylesheet" type="text/css" href="homepage.css">
</head>
<body>
        <div class="logo">
            <img src="image/protection2.gif" alt="Protection">
        </div>
            <button class="button"  onclick="location.href='video.php'">
                <img class="gallery-icon" src="image/2023-06-02 12.26.22 - lamborghini.png"><br>
                Gallery
            </button>
            <button class="button" onclick="location.href='Price_List.php'">
                <img class="gallery-icon" src="image/lamborghini-5120x2880-11123.jpeg"><br>
                Price List
            </button>
            <button class="button" onclick="location.href='Survey.php'">
                <img class="gallery-icon" src="image/orange car.png"><br>
                Questionnare
            </button>
</body>
</html>

修改后的CSS

.button {
    font-family: 'Bebas Neue', sans-serif;
    font-size: 40px;
    /* 启用flex垂直布局,实现内部元素居中 */
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    background-color: rgba(255, 255, 255, .65);
    color: black;
    width: 100%;
    max-width: 300px;
    /* 替换百分比height为min-height,避免布局异常 */
    min-height: 180px;
    margin: 0 auto 20px;
    /* 修正padding语法错误,调整内边距 */
    padding: 20px;
    border-radius: 8px;
    border: 3px solid orange;
}

.gallery-icon {
    width: 75px;
    border-radius: 50px;
    border: 3px solid orange;
    /* 确保图片水平居中,flex布局下可省略,添加后更稳妥 */
    margin: 0 auto 10px;
}

.button:hover {
    background-color: orange;
    color: white;
}

关键改动说明

  1. 将.button设置为display: flex,flex-direction: column让图片和文字垂直排列,align-items: center实现水平居中,justify-content: center实现垂直居中
  2. 修正padding的语法错误,移除多余的反引号
  3. 将重复的idgallery-icon改为class,符合HTML规范
  4. 给图片添加margin: 0 auto确保水平居中,同时调整图片与文字的间距
  5. 替换百分比height为min-height,避免按钮高度随父元素异常变化
  6. 合并重复的.button:hover样式,精简代码

内容的提问来源于stack exchange,提问作者BlueQwater

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 20:07:00