如何使用 CSS 使 1 个 div 居中对齐,其他则向右浮动

sha*_*dar 5 css

我想让我的 div2 居中对齐,div3 位于右侧。

期望什么

我尝试使用文本对齐:主 div 的中心并使浮动向右到 div3 来做到这一点,但它通过考虑主 div 的剩余部分来使其居中对齐。我已经给主 div 赋予了 display: inline-flex

怎么了

<div style="height: 40px;width:120px;background-color: yellow;align-items: center;">

<div style="height: 20px;width:20px;background-color: red;">
  Hello
</div>

<div style="height: 20px;float: right;width:20px;background-color: red;">
</div>
</div>
Run Code Online (Sandbox Code Playgroud)

小智 6

请尝试使用此代码:

<div style="height: 40px;width:120px;background-color: yellow;align-items: center; position:relative;">

<div style="height: 20px;width:40px;background-color: red; overflow:auto; margin:0 auto">
  Hello
</div>

<div style="height: 20px;position:absolute; right:0px; top:0px; width:20px;background-color: red;">
</div>
</div>
Run Code Online (Sandbox Code Playgroud)


Cha*_*ani 1

添加style="margin: auto;"到您的 div2 元素。还有 style="margin-left: auto;"你的 div3 元素。

<div style="height: 40px;width:120px;background-color: yellow;align-items: center;">

<div style="margin:auto; height: 20px;width:20px;background-color: red;">
  Hello
</div>

<div style="margin-left:auto; height: 20px;float: right;width:20px;background-color: red;">
</div>
</div>
Run Code Online (Sandbox Code Playgroud)