将父级 DIV 水平居中对齐

3

我有这个:

figure {
  display:inline-block;
}

figcaption {
  width:0;
  min-width:100%;
}
<figure>
   <img src="https://i.imgur.com/k1Crowy.jpg" width="200">
   <figcaption> This is some random text that should not expand the figure tag beyond the width of the img tag </figcaption>
</figure>

如何将<figure>标签居中对齐,不破坏figcaption宽度的设置不添加外部div?

我尝试过的方法

我可以对子标签使用margin:0 auto的方法,但这会破坏figcaption宽度的设置。

3个回答

3

使用display:table可以获得类似inline-block的行为,然后您可以考虑使用margin:auto

figure {
  display:table;
  margin:auto;
}

figcaption {
  width:0;
  min-width:100%;
}
<figure>
   <img src="https://i.imgur.com/k1Crowy.jpg" width="200">
   <figcaption> This is some random text that should not expand the figure tag beyond the width of the img tag </figcaption>
</figure>


1

figure中添加下面的CSS

  margin-left: 50%;
  transform: translateX(-50%);

figure {
  display: inline-block;
  margin-left: 50%;
  transform: translateX(-50%);
}

figcaption {
  width: 0;
  min-width: 100%;
}
<figure>
  <img src="https://i.imgur.com/k1Crowy.jpg" width="200">
  <figcaption> This is some random text that should not expand the figure tag beyond the width of the img tag </figcaption>
</figure>


请注意,由于 margin-left 将被添加到元素的宽度中,在小屏幕上这可能会产生不必要的溢出,从而超出容器的总宽度。更准确地说,当 figure 元素的宽度也等于父元素宽度的 50% 时,此现象将会发生。 - Temani Afif
这是一个带有更大图像的示例:https://jsfiddle.net/gdmovrnt/ 由于图形宽度 + 50%边距超过总宽度,因此您在底部看到了滚动条,这是不需要的溢出 - Temani Afif

-1

对于图片或图形标签,您可以使用:

display: block;
margin:auto

对于每个标签,您可以使用:

position: absolute;
left: 50%;
top:50%;
transform: translate(-50%, -50%)

在这种情况下,你的代码必须是:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        div {
            width: 500px;
            height: 400px;
            border: 1px solid grey
        }

        .hoz {
            position: absolute;
            left:50%;
            transform: translate(-50%);
        }
        .center {
            position: absolute;
            left:50%;
            top:50%;
            transform: translate(-50%,-50%);
        }
    </style>
</head>
<body>

<div>
    <figure>
        <img src="https://i.imgur.com/k1Crowy.jpg" width="200" style="display: block;margin:auto">
        <figcaption> This is some random text that should not expand the figure tag beyond the width of the img tag </figcaption>
    </figure>
</div>

<div style="position: relative">
    <figure class="hoz" style="margin:0">
        <img src="https://i.imgur.com/k1Crowy.jpg" width="200">
        <figcaption> This is some random text that should not expand the figure tag beyond the width of the img tag </figcaption>
    </figure>
</div>

<div style="position: relative">
    <figure class="center" style="margin:0">
        <img src="https://i.imgur.com/k1Crowy.jpg" width="200">
        <figcaption> This is some random text that should not expand the figure tag beyond the width of the img tag </figcaption>
    </figure>
</div>

</body>
</html>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接