将固定宽度的可变高度 div 水平居中,使其溢出其父级

问题描述 投票:0回答:2

考虑这个 HTML:

<body style="max-width: 50px; border: 1px solid black; margin: 0 auto;">
<p>This is some text</p>

<div style="width: 100px; background: yellow">
<p>Some wider content</p>
</div>

<p>Some more narrow text</p>
</body>

我想将黄色框居中,使其溢出

body
。我在 StackOverflow 上查看了很多关于如何执行此操作的答案,然后通常涉及将
div
设置为相对定位并将其包装在另一个 div 中,但随后您始终需要显式设置包装器 div 的高度。

有没有办法让div水平居中而不影响垂直布局的工作方式?

另请注意,我确实想将其居中;不仅仅是抵消固定金额。

html css css-position
2个回答
1
投票

在该 div 上使用以下设置:

position: relative;
left: 50%;
transform: translateX(-50%);

这会将 div 向右移动父级宽度的 50%,然后向左移动其自身宽度的 50%,从而使其水平居中。

position: relative;
是使这些设置发挥作用所必需的。

请注意,使用

position: relative;
仍然保留 div 在文档流中占据的(水平)空间,而使用
position: absolute
时则不会出现这种情况。

body {
  max-width: 50px;
  border: 1px solid black;
  margin: 0 auto;
}

div {
  position: relative;
  left: 50%;
  transform: translateX(-50%);
  width: 100px;
  background: yellow;
}
<body>
  <p>This is some text</p>

  <div>
    <p>Some wider content</p>
  </div>

  <p>Some more narrow text</p>
</body>


0
投票

你可以使用弹性盒。请注意,这将改变边距与子项交互的方式。

body {
  display: flex;
  flex-direction: column;
  align-items: center;
}
<body style="max-width: 50px; border: 1px solid black; margin: 0 auto;">
<p>This is some text</p>

<div style="width: 100px; background: yellow">
<p>Some wider content</p>
</div>

<p>Some more narrow text</p>
</body>

© www.soinside.com 2019 - 2024. All rights reserved.