在html中将文本居中同时保持左对齐?

时间:2020-04-30 16:21:16

标签: html css text

我浏览了许多有关此主题的文章,但传统的解决方案似乎无效。我很可能在做错事,但看不到。我正在尝试在div中居中放置文本,同时保持左对齐。这是我的代码/标记:

HTML

<div class="home">
    <div class="title">
        Hi, I'm <a href="#">name</a>.  This is some of my <a href="#">work</a>.
    </div>
</div>

CSS

.home {
    padding: 120px 75px 0px 75px;
    margin: 0 0 200px 0;
    width: calc(100% - 150px);
    height: auto;
    text-align: center;
}
   .title {
   display: inline-block;
   text-align: left;
   color: var(--text-primary);
}

目前,我已经进行了设置,因此标题div中的文本保持左对齐,标题div在主div内居中(至少我认为是这样。)我也尝试了flex box ,但无济于事。我认为问题与以下事实有关:h1标签中的文本会自动换行,并在右侧留有空间(在下面的红色中选择)。这是我的意思:

感谢您的光临,我非常感谢您的建议!

5 个答案:

答案 0 :(得分:0)

我认为你需要这个。

.home {
    padding: 50px 0;
    margin: 0 0 200px 0;
    width: calc(100% - 150px);
    height: auto;
    display: flex;
    justify-content: center;
    background:red;
}
.title {
   display: inline-block;
   color: var(--text-primary);
   background: yellow;
   width: calc(100% - 100px);
   text-align: center;
}
<div class="home">
    <div class="title">
        Hi, I'm <a href="#">name</a>.  This is some of my <a href="#">work</a>.
    </div>
</div>

答案 1 :(得分:0)

.title {
    display: inline-block;
    text-align: center;
    color: var(--text-primary);
    float:left;
}

答案 2 :(得分:0)

当我想将任何内容居中时,我通常会尝试这样做,所以我希望它可以与您一起使用。

subtractOne(0)

答案 3 :(得分:0)

尝试将“首页”宽度设置为100%,将“标题”设置为margin-left:auto; margin-right:自动

答案 4 :(得分:0)

我设法通过将标题div“收缩包装”到其中的文本来使其工作,以使文本居中,然后将home div用作标题div所在的flex框居中。

.home {
    padding: 5% 0;
    margin-top: 10%;
    width: 100%;
    height: auto;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 5.5rem;
    font-weight: 800;
    color: var(--text-primary);
}

.title {
    width: max-content;
}

希望这可以帮助其他有此问题的人!