旁边有文字的可缩放图像

时间:2019-04-23 10:06:27

标签: html css

我正在尝试使文本附近的图像可缩放并响应。当前,当我运行html页面时,div如下所示:

enter image description here

这很好,但是当我尝试调整窗口大小时,它将看起来像这样: enter image description here

当文字在图片下方换行时,我想将图片样式设置为width: 100%;

在文本下方时,是否有任何方法可以使图像缩放,但在有足够的位置将文本放置在图像附近时,是否可以保留它? 它应该看起来像这样:

enter image description here

我当前的代码

.cake {
  background-color: white;
  overflow: hidden;
  padding: 5px;
  margin-bottom: 5px;
  margin-top: 5px;
}

.cake p {
  margin-bottom: 0;
  text-align: justify;
}

.cake>.price {
  margin-right: 10px;
}

.cake>img {
  padding-right: 20px;
  float: left;
  overflow: hidden;
  width: 100%;
  min-width: 240px;
  max-width: 300px;
  height: 200px;
  display: block;
  object-fit: cover;
}

.price {
  float: right;
}
<div class="cake">
  <img src="https://i.imgur.com/xWRtGkj.jpg">
  <h4>Cheesecake</h4>
  <p>
    Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.
  </p>
  <span class="price">45</span>
</div>

2 个答案:

答案 0 :(得分:3)

您可以为此使用flexbox,但是如果您不想将代码更改为flexbox,则可以像下面这样

.cake {
    background-color: white;
    overflow: hidden;
    padding: 5px;
    margin-bottom: 5px;
    margin-top: 5px;
}
.cake p {
    margin-bottom: 0;
    text-align: justify;
}
.cake > .price {
    margin-right: 10px;
}
.cake > img {
    padding-right: 20px;
    float: left;
    overflow: hidden;
    width: 100%;
    min-width: 240px;
    height: 200px;
    display: block;
    object-fit: cover;
}
.price {
    float: right;
}

@media (min-width: 430px) {
    .cake > img {
        max-width: 300px;
    }
}
<div class="cake">
  <img src="https://i.imgur.com/xWRtGkj.jpg">
  <h4>Cheesecake</h4>
  <p>
    Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.
  </p>
  <span class="price">45</span>
</div>

答案 1 :(得分:0)

您可以使用媒体查询Using media queries

.cake {
  background-color: white;
  overflow: hidden;
  padding: 5px;
  margin-bottom: 5px;
  margin-top: 5px;
}

.cake p {
  margin-bottom: 0;
  text-align: justify;
}

.cake>.price {
  margin-right: 10px;
}

.cake>img {
  padding-right: 20px;
  float: left;
  overflow: hidden;
  width: 100%;
  min-width: 240px;
  max-width: 300px;
  height: 200px;
  display: block;
  object-fit: cover;
}

.price {
  float: right;
}

@media only screen and (max-width: 768px) { /*put the breakpoint where the text wrap*/
  .cake p {
     width: 100%;
   }
}