首页 > 解决方案 > 如何使用 Bootstrap 在另一个 DIV 的左侧显示 DIV

问题描述

我想创建一个棋盘样式HTML的页面 ( ) ,因此第一行的图像位于内容的左侧,第二行的图像位于内容的右侧。

从语义上讲,我可以改变 HTML 的结构来实现这一点,但是有没有办法纯粹使用 CSS + Bootstrap 4 来做到这一点,所以 HTML 不需要改变。

我最初有一个类“ left-img”和“ right-img”来实现这一点,但没有成功。

目前我在我CSS的每个事件元素中都有这个。

.checker:nth-child(even) .img-wrapper {
    float:right;
}
.checker:nth-child(odd) .img-wrapper {
    float:left;
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet"/>



<div class="row checker">
    <div class="col-lg-6">
        <div class="">
            <h2>The Title</h2>  
            <div class="">
                some text
            </div>
        </div>
    </div>
    <div class="col-lg-6 img-wrapper">
        <img src="https://via.placeholder.com/140x100" alt="">
    </div>
</div>
<div class="row checker">
    <div class="col-lg-6">
        <div class="">
            <h2>The Title</h2>  
            <div class="">
                some text
            </div>
        </div>
    </div>
    <div class="col-lg-6 img-wrapper">
        <img src="https://via.placeholder.com/140x100" alt="">
    </div>
</div>

完整示例

我的代码笔https://codepen.io/s-mcdonald/pen/qBZvwyX?editors=1100

标签: htmlcssbootstrap-4

解决方案


我希望 css 和 html 的这些变化对你有帮助!!!

.checker:nth-child(odd) > .col-lg-6:last-of-type{
    float:left !important;
}

.checker:nth-child(even) > .col-lg-6:first-of-type{
    float:left !important;

}

img{
  width:100px;
}

.col-lg-6{
  float:right;
}

.row{
  float:right;
  width:100%;
}
<div class="row checker">
    <div class="col-lg-6">
        <div class="">
            <h2>The Title</h2>  
            <div class="">
                some text
            </div>
        </div>
    </div>
    <div class="col-lg-6 img-wrapper">
        <img src="https://cdn.jpegmini.com/user/images/slider_puffin_jpegmini_mobile.jpg" alt="">
    </div>
</div>
<div class="row checker">
    <div class="col-lg-6">
        <div class="">
            <h2>The Title</h2>  
            <div class="">
                some text
            </div>
        </div>
    </div>
    <div class="col-lg-6 img-wrapper">
        <img src="https://cdn.jpegmini.com/user/images/slider_puffin_jpegmini_mobile.jpg" alt="">
    </div>
</div>


推荐阅读