如何在不将div包裹在容器中的情况下连续对齐div?

时间:2018-10-29 09:38:32

标签: css

如何在卡片内对齐两个div,即“标签1”和“标签2”,如下图所示?

enter image description here

.card {
  position: relative;
}

.card .label1 {
  display: inline-block;
  position: absolute;
  bottom: 16px;
}

.card .label2 {
  display: inline-block;
  position: absolute;
  bottom: 16px;
}
<div class="card">
  <div class="image"><img src="http://www.fillmurray.com/140/100" /></div>
  <div class="title">Title</div>
  <div class="description">
    <p>Lorem ipsum dolor sit amet.</p>
  </div>
  <div class="label1">Label 1</div>
  <div class="label2">Label 2</div>
</div>

我需要对齐“标签1”和“标签2”,因此它们位于一行中,并且彼此跟随。也可能发生其中一个标签不存在的情况,因此我无法为每个标签都固定位置。我无法将标签放在容器元素中(例如,我无法将label1label2包装在<div>中)。

2 个答案:

答案 0 :(得分:1)

Flexbox可以做到这一点,而无需其他包装器。

这里的窍门是将标签上方的容器设置为100%宽并将内容居中。

.card {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  width: 80%;
  border: 1px solid red;
  margin: 1em auto;
  justify-content: space-around;
  padding: 1em;
}

.image,
.title,
.description {
  flex: 1 0 100%;
  text-align: center;
}

.label1,
.label2 {
  background: red;
  padding: 1em;
}
<div class="card">
  <div class="image"><img src="http://www.fillmurray.com/140/100" /></div>
  <div class="title">Title</div>
  <div class="description">
    <p>Lorem ipsum dolor sit amet.</p>
  </div>
  <div class="label1">Label 1</div>
  <div class="label2">Label 2</div>

</div>

答案 1 :(得分:0)

希望对您有帮助

<!DOCTYPE html>
<html lang="en">

<head>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <style>
    .card {
      width: 250px;
      height: 250px;
      border: 1px solid red;
      display: flex;
      padding: 5px;
      text-align: center;
      justify-content: space-around;
    }
    
    .label {
      padding: 10px;
      width: 80px;
      height: 20px;
      text-align: center;
      border: 1px solid black;
    }
    
  </style>
</head>

<body>
  <div class="card">
      <div class="label">Label 1</div>
      <div class="label">Label 2</div>
  </div>
</body>

</html>