首页 > 解决方案 > 将 div 居中在另一个 div 中的最佳方法是什么?

问题描述

到目前为止,我一直在尝试创建这张图片中显示的基本网站布局。 https://imgur.com/a/JhURder

它包括一个灰色背景,内部有一个居中的 div,背景为白色。左侧居中图像,右侧居中文本等。

我是 twitter bootstrap 的大力倡导者,到目前为止我已经实现了这一点。(反应风格)

            <div class="container-fluid" style={{
                'background-color' : 'rgb(224,225,226)',
                'height' : '40vh'
            }}>
                <div class="row">
                    <div class="col-1 text-center"> Test </div>

                    <div class="col-10 text-center" style={{
                        'height' : '30vh',
                        'background-color' : 'rgb(255,255,255)',
                        'margin-top' : '5vh'
                    }}>

                    centered

                    </div>

                    <div class="col-1 text-center">test</div>
                </div>
            </div>

到目前为止,它已经成功了一半。但老实说,我有点给了我们,因为它变成了一个嵌套的混乱。对于网站开发,我一直都知道他们是一条更大的路,所以我来这里是为了让人们到目前为止烤我的尝试,并且可以让我以适当的方式实现我的目标。

标签: javascripthtmlcssreactjs

解决方案


这里有一些关于如何实现它的想法。

https://codepen.io/Warisara-L/pen/wOMxwR

// HTML
<div class="wrapper" id="solution-1">
  <div class="inner">1</div>
</div>

// SCSS
#solution-1 {
  display: grid;
  .inner {
    margin: auto;
  }
}

#solution-2 {
  display:flex;
  justify-content: center;
  align-items: center;
}

#solution-3 {
  position: relative;
  .inner {
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
  }
}

#solution-4 {
  display: flex;
  .inner {
    margin: auto;
  }
}

#solution-5 {
  display: grid;
  justify-content: center;
  align-items: center;
}

#solution-6 {
  position: relative;
  .inner {
    position: absolute;
    margin: auto;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
  }
}

#solution-7 {
  height: 120px;
  line-height: 120px;
  text-align: center;
  .inner {
    display: inline-block;
    vertical-align: middle;
  }
}

#solution-8 {
  display: flex;
  .inner {
    align-self: center;
    margin: 0 auto;
  }
}

祝你有美好的一天先生:)


推荐阅读