【问题标题】:Div cannot be center alignedDiv 不能居中对齐
【发布时间】:2022-01-10 08:52:58
【问题描述】:

问题

当我尝试使用代码时(见下文),只有当我使用width: 100px; 时,div 才会居中。

<div style="border: solid 1px black; width: 100px; height: 100px; background-color: blue; margin-left: auto; margin-right: auto;">

由于我想为文本分配更长的宽度并将宽度设置为500px,因此 div 不再居中。

<div style="border: solid 1px black; width: 500px; height: 100px; background-color: blue; margin-left: auto; margin-right: auto;">

问题 #2

svg 没有居中

<div class="col-xl-3 col-lg-3 col-sm-6">
    <div class="ud-single-feature wow fadeInUp" data-wow-delay=".25s" >
        <div class="ud-feature-icon" >
            <i class="lni lni-layers"></i>
        </div>
        <div class="ud-feature-content" style="position:absolute; width: 100%; text-align: center;">

            <h3 class="ud-feature-title" style="text-align: center;">test</h3>
            <p class="ud-feature-desc" style="text-align: center;">
                test
            </p>
            <!--                        <a href="javascript:void(0)" class="ud-feature-link">
                                        Learn More
                                    </a>-->
        </div>
    </div>
</div>

【问题讨论】:

标签: javascript html css center


【解决方案1】:

虽然您的问题没有定义您想要的目标,但使用 margin-left 或 right 并不能证明页面的中心点是正确的。相反,请考虑使用position: fixed 以便在页面中准确居中。

这也应该意味着您可以根据需要设置 div 的尺寸。

<div style="background: blue; width: 100px; height: 100px; position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%)">Div should be properly centred in page.</div>

【讨论】:

  • 我现在已经更新了问题,请看更新后的问题。
【解决方案2】:

您可以像这样将 div 设置为另一个 div 的子级:

<div style="justify-content: center; align-items: center; display: flex;">
  <div style="border: 1px solid black; width: 500px; height: 100px; background-color: blue;">

  </div>
</div>

【讨论】:

  • 我现在已经更新了问题,请看更新后的问题。
  • @etoby。您能否提供完整的 html 代码而不仅仅是 div ?这将更容易回答。
  • 问题已经解决了,问题是我要换班了。
  • @etoby。好的没问题。
猜你喜欢
相关资源
最近更新 更多
热门标签