首页 > 解决方案 > 如何在保持宽度的同时将标题移动到右侧?

问题描述

我在保持给定宽度的同时将 h2 标题移动到屏幕右侧时遇到问题。我试过 display: flex 和 float: right 但我似乎无法弄清楚如何有效地将 h2 div 对齐到屏幕的右侧。我的代码在这里:http: //jsfiddle.net/b62tg9un/19/

<div class="container">
    <h1>Example Title</h1>
    <h2>This is a test sentence to work on my html and css code.</h2>
</div
h2 {
    width: 60%;
    float: right;
}
.highlight {
    display: inline-block;
}
.container {
        display: flex;
        flex-direction: column;
        text-align: right;
        justify-items: right;
}

谢谢

标签: css

解决方案


如果您希望 flex 容器中的项目与容器的右侧对齐,您应该使用align-items: flex-end

h2 {
  width: 60%;
}

.container {
  align-items: flex-end;
  display: flex;
  flex-direction: column;
}

这仍然会将 h1 和 h2 放在一列中,但 h2 仅占宽度的 60% 并向右对齐。


推荐阅读