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

如何将H1元素定位在div右上角?仿命运2角色选择卡样式

解决方案:将数字定位到div右上角

问题描述

我希望让数字100显示在div的右上角,目前已设置右对齐但它仍位于底部,有没有简单的CSS修复方法?我想实现类似《命运2》中角色选择卡片的样式。

当前代码:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <title>D2</title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="../styles/styles.css">
    </head>
    <body>
        <div class="titan">
            <h2>Titan</h2>
            <h3>Exo Male</h3>
            <h1>100</h1>
        </div>
        <script src="../js/index.js" async defer></script>
    </body>
</html>
@import url('https://fonts.googleapis.com/css2?family=Roboto:wght@300');
body{
    background-image: url(../assets/bg.PNG);
    background-repeat: no-repeat;
    background-size: cover;      
}
.titan{
    background-image: url('../assets/titan.PNG');
    width: 474px;
    height: 96px;
}
h1{
    color: #31ccf3;
    font-family: 'Roboto', sans-serif;
    padding-left: 5rem;
    float: right;
}
h2{
    color: white;
    font-family: 'Roboto', sans-serif;
    padding-left: 5rem;
}
h3{
    color: #c9c9c9;
    font-family: 'Roboto', sans-serif;
    padding-left: 5rem;
    font-size: 1em;
}

修复方法

用绝对定位就能轻松实现,具体调整:

  • 给父容器.titan添加position: relative,让内部绝对定位元素以此为基准
  • 给包含数字的h1设置position: absolute,通过top: 0和right: 1rem控制位置,同时去掉多余的float和padding-left
  • 清除标题标签的默认margin,避免文字位置偏移

修改后的CSS:

@import url('https://fonts.googleapis.com/css2?family=Roboto:wght@300');
body{
    background-image: url(../assets/bg.PNG);
    background-repeat: no-repeat;
    background-size: cover;      
}
.titan{
    background-image: url('../assets/titan.PNG');
    width: 474px;
    height: 96px;
    position: relative; /* 添加相对定位 */
}
h1{
    color: #31ccf3;
    font-family: 'Roboto', sans-serif;
    position: absolute; /* 绝对定位 */
    top: 0; /* 顶部对齐 */
    right: 1rem; /* 右侧留一点间距,可按需调整 */
    margin: 0; /* 清除默认margin避免偏移 */
}
h2{
    color: white;
    font-family: 'Roboto', sans-serif;
    padding-left: 5rem;
    margin: 0; /* 清除默认margin */
    padding-top: 0.5rem;
}
h3{
    color: #c9c9c9;
    font-family: 'Roboto', sans-serif;
    padding-left: 5rem;
    font-size: 1em;
    margin: 0; /* 清除默认margin */
}

调整后数字100会固定在.titan容器的右上角,左侧标题文字的排版也更贴合《命运2》角色卡片的样式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 03:45:49