RWD:垂直居中2个div

时间:2016-04-26 20:41:45

标签: html css twitter-bootstrap responsive-design

我希望垂直居中2 div,我厌倦了使用vertical-align: middle,但这不起作用,也尝试了margin,但不能正常工作。

我可以做些什么来将这两个中心化?

CODE

.about{
    text-align: center;
    position: relative;
}

.aboutImg {
    position: absolute;
    width: 100%; 
    left: 0px;
}
.textContainer {
    position: relative; 
    width: 60%; 
    margin-left: auto;
    margin-right: auto;
    z-index: 20;
}
<div class="about" id="aboutStrings">
  <img class="aboutImg" src="about1.jpg">
  <div class="textContainer">
    <h1>About Strings</h1>
    <p>Strings Ramen Shop pulls a piece of Japanese Culture to Chicago, we can be found in the heart of Chinatown, directly across from New Chinatown Square. While other restaurants may serve ramen along with a number of other entrees, Strings Ramen focuses specifically on ramen. Along with ramen, Strings will also offer the appetizing oden, a Japanese winter street food. On top of tasting delightful, the ramen at Strings is also affordable but gives the option of adding more deluxe ingredients. The menu includes four types of ramen broth with a variety of high-end ingredients that are added to make the dish even more delectable.
                One of the major aspects of Strings is the noodles themselves. Strings will make fresh noodles daily using only their unique dough mixer and noodle maker imported straight from Japan. The use of fresh noodles, and genuine broth combined with passion and the use of only the best ingredients will certainly set Strings Ramen Shop apart.</p>
  </div>
</div>

我还希望图像根据屏幕大小调整大小,最重要的是,文本应始终包含在图像中。因此,如果屏幕变小时段落的高度拉伸到500px,则应自动调整图像高度以包含文本。我已经加入了Bootstrap css。

3 个答案:

答案 0 :(得分:0)

不使用Flexbox,您可以使用一些绝对定位来实现这一目标。

.about {
  position: relative;
}
.textContainer {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
}

这会使textContainer容器内的about垂直居中。

CSS Tricks为此here提供了很好的资源。

答案 1 :(得分:0)

vertical-align:middle仅适用于inline-block级元素

在你的css中试试这个

.about{
  text-align: center;
}
.aboutImg {
  width: 40%; 
  display: inline-block;
  vertical-align:middle;
}
.textContainer {
  width: 40%; 
  display: inline-block;
  vertical-align:middle;
}

答案 2 :(得分:0)

在使用之前阅读vertical-align: middle;

当您使用vertical-align: middle;时,父元素的高度必须大于其内容,否则它不会垂直居中。

注意:值0不应指定单位。

这是一个简单的weave,可以准确显示它是如何完成的。

html, body {
  margin: 0;
  padding: 0;
  height: 100%;
}

body {
  background: rgb(0, 28, 66);
  font: 20px arial;
}

header {
  display: table;
  width: 100%;
  height: 100%;
  color: #fff;
  text-align: center;
  overflow: hidden;
}

nav {
  display: table-cell;
  vertical-align: middle;
}
<header>
  <nav>
    <h1>
    	Hello
    </h1>
  </nav>
  <nav>
    <h1>
    	world!
    </h1>
  </nav>
</header>