将父div水平对齐到中心

时间:2019-04-15 10:38:27

标签: css

我有这个:

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>

如何在没有添加外部div的情况下将<figure>标签对准中心, 不破坏figcaption宽度修正? / p>

到目前为止我已经尝试过的

我可以对子标记执行margin:0 auto方法,但这会破坏figcaption宽度固定。

3 个答案:

答案 0 :(得分: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 :(得分:1)

CSS下面添加到figure

  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>

答案 2 :(得分:-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>