CSS-下方的图片和文字居中

时间:2019-06-30 23:14:24

标签: html css image

我想显示一个居中的图像,并在其下方显示居中且带有边框的文本,其宽度等于其容器的宽度。我使用:

<!DOCTYPE html>
<html>
<head>
<style>
.d1 {
    text-align: center;
}
.d2 {
    border: 1px solid red;
    display: inline-block;
}
</style>
</head>
<body>

<div class="d1">
    <img src="smiley.gif"><br>
    <div class="d2">This is some text</div>
</div>

</body>
</html>

这很好用,但据我所读,使用<br>表示语义HTML较差,应避免使用。有没有不使用<br>的方法? 谢谢

4 个答案:

答案 0 :(得分:1)

Flexbox进行救援:

.d1 {
    display: flex;
    flex-flow: column;
    justify-content: center;
}
.d2 {
    border: 1px solid red;
}

img, .d2{
  margin: 0 auto;
}
<div class="d1">
    <img src="https://placekitten.com/200/300">
    <div class="d2">This is some text</div>
</div>

答案 1 :(得分:1)

要使用的语义上正确的元素是HTML5 figure元素(documentation here)-这是一个块级元素,包含figcaption元素和image元素在里面。

figcaption可以是第一个孩子(即-在图像之前)或最后一个孩子(在图像之后),并且也是块级元素,并且可以以css为中心。

<!DOCTYPE html>
<html>
<head>
<style>
figure {
    text-align: center;
}

figcaption {
 margin-bottom: 10px;
}

</style>
</head>
<body>

<figure>
   <figcaption>This is a fluffy kitten</figcaption>
   <img src="https://cdn.unifiedcommerce.com/content/product/small/30106.jpg" alt="fluffy kitten" width="100">
</figure>

</body>
</html>

答案 2 :(得分:0)

尝试使用div封装图像。 div是一个块元素,这意味着它将占据父宽度的100%。对于您而言,如果img标签位于div内,则div之外的所有内容将自动位于下一行。

img {
  max-width: 100px;
}

.d1 {
  text-align: center;
}

.d2 {
  border: 1px solid red;
  display: inline-block;
}
<div class="d1">
  <div>
    <img src="https://demo-res.cloudinary.com/image/upload/sample.jpg">
  </div>
  <div class="d2">This is some text</div>
</div>

答案 3 :(得分:0)

您可以尝试使用此方法。只需在文本部分使用margin而不是<br>标签。然后,为了将图像和文本都定位在中心,请使用以下属性:

display: flex;
justify-content: center;
align-items: center;
flex-flow: column;

<!DOCTYPE html>
<html>
<head>
<style>
.d1 {
    display: flex;
    justify-content: center;
    align-items: center;
    flex-flow: column;
}
.d2 {
    border: 1px solid red;
    margin-top: 5px;
}
</style>
</head>
<body>
<div class="d1">
    <img src="https://www.w3schools.com/howto/img_snow.jpg">
    <div class="d2">This is some text</div>
</div>
</body>
</html>