为什么CSS浮动左右不工作?

z9gpfhce  于 2023-03-20  发布在  其他
关注(0)|答案(1)|浏览(123)

我想让图片在文本的左边,但是浮动似乎不起作用。我想格式化它,让图片在div中浮动在文本的右边。下面是我的代码:

<div class="say-hello">
            <img src="images/say-hello.jpg" alt="Person placing macarons on top of cake">
            <div class="say-hello-text">
                <h2>Say Hello</h2>
                <p>In the mood for something sweet? We'd love to make your next event special with something Positively Delicious. Whether you're looking for a classic birthday cake or a unique cupcake assortment, we've got you covered.</p>
                <div class="say-hello-button">
                    <a class="button" href="#">Contact us</a>
                </div>
            </div>
        </div>
.say-hello {
    width: 80%;
    max-width: 100%;
    height: 100%;
    padding: 30px;
    margin: auto;
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    border-radius: 8px;
  }
  .say-hello img {
    object-fit: cover;
    width: 50%;
    border: none;
    float: right;
    padding: none;
    margin-left: 0;
    margin-right: 0;
  }
  .say-hello-text {
    text-align: center;
    align-self: center;
    width: 40%;
    padding-right: 4%;
    float: left;
  }
fnvucqvd

fnvucqvd1#

flex容器中的float属性被忽略:你正在容器div中使用"display:flex"(带有class .say-hello),只需删除display flex,浮动就可以正常工作:

.say-hello {
    width: 80%;
    max-width: 100%;
    height: 100%;
    padding: 30px;
    margin: auto;
    /*display: flex;*/
    flex-wrap: wrap;
    justify-content: space-between;
    border-radius: 8px;
  }
  .say-hello img {
    object-fit: cover;
    width: 50%;
    border: none;
    float: right;
    padding: none;
    margin-left: 0;
    margin-right: 0;
  }
  .say-hello-text {
    text-align: center;
    align-self: center;
    width: 40%;
    padding-right: 4%;
    float: left;
  }
<div class="say-hello">
            <img src="https://assets.codepen.io/t-1/user-default-avatar.jpg?format=auto&version=0&width=80&height=80" alt="Person placing macarons on top of cake">
            <div class="say-hello-text">
                <h2>Say Hello</h2>
                <p>In the mood for something sweet? We'd love to make your next event special with something Positively Delicious. Whether you're looking for a classic birthday cake or a unique cupcake assortment, we've got you covered.</p>
                <div class="say-hello-button">
                    <a class="button" href="#">Contact us</a>
                </div>
            </div>
        </div>

相关问题