首页 > 解决方案 > 使用 CSS 获取等长的兄弟姐妹

问题描述

我有一个问题,即元素按未知图像的尺寸自动调整大小。我希望该图像的同级元素受到与图像设置相同的宽度的约束。不使用 javascript。

我已经设置了一支笔来说明我的意思:

.container{
    display: table
}
.img-wrapper{
    line-height: 0
}
.info{
    display: table-cell;
    vertical-align: middle;
    background: black;
    color: white;
}

.info p{
  margin: 0 2vmin
}
<div class="container">
      <div class="img-wrapper">
        <img src="https://picsum.photos/600/500">
      </div>
      <div class="info">
        <p>Lorem ipsum </p>
      </div>
</div>

https://codepen.io/Slagon/pen/oNePqNo

有可能.info一样宽.img-wrapper吗?(忽略此笔中预定义的尺寸)。

标签: htmlcssflexbox

解决方案


我使用Bootstrap来解决这个问题。本质上它的工作原理是一个普通的网页跨度12 columns。因此,在这种情况下,我将你们每个人的 div 放在 a 中col-6,以便每个元素占据页面的一半。这两个 col-6 跨度都包含在row. 请看下文。

.container {
    display: block;
    justify-content: center;
}
.img-wrapper {
    line-height: 0;
}
.info {
    display: flex;
    background: black;
    color: white;
    width: 100%;
    height: 100%;
}

.col-6 > .img-wrapper > img {
  width: 100%;
  height: 100%;
  margin: 0;
}

div.col-6 {
  padding: 0;
}

p {
  width: 100%;
  text-align: center;
  margin: auto;
}
<head>
   <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>

<body>

<div class="container">
<div class="row">
      <div class="col-6">
         <div class="img-wrapper">
            <img src="https://picsum.photos/600/500">
         </div>
      </div>
      <div class="col-6">
         <div class="info">
            <p>Lorem ipsum </p>
         </div>
      </div>
</div>
</div>

</body>

点击整页


推荐阅读