CSS在图像上垂直和水平放置文本

时间:2016-09-06 20:36:50

标签: html css

我试图将div banner_title垂直和水平地居中于另一个div中......就像这样......



.box {
  text-align: center;
}
.banner_title {
  font-size: 32px;
  position: absolute;
  top: 50%;
  width: 100%;
}
.banner_title > div {
  background: rgba(0, 0, 0, 0.7) none repeat scroll 0 0;
  color: #fff;
  padding: 15px;
}

<div class="box">
  <img src="http://dummyimage.com/1000x400/b895b8/fff.jpg&text=+">
  <div class="banner_title">
    <div>
      THIS MESSAGE IS A TEST MESSAGE
    </div>
    <button>
      This is a test button
    </button>
  </div>
</div>
&#13;
&#13;
&#13;

也在https://jsfiddle.net/j90gaawb/

这对我不起作用,有人可以帮忙吗?

这就是我想要实现的目标......

enter image description here

3 个答案:

答案 0 :(得分:1)

这是你在找什么?

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

.banner_title {
  position: absolute;  
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.banner_title > div {
   background: rgba(0, 0, 0, 0.7) none repeat scroll 0 0;color: #fff;
   padding: 15px;
}

小提琴:https://jsfiddle.net/j90gaawb/1/

答案 1 :(得分:1)

我会推荐以下方法

&#13;
&#13;
.box {
  text-align: center;
  display: table;
  width: 100vw;
  height: 100vh;
}
.banner {
  font-size: 32px;
  display: table-cell;
  vertical-align: middle;
  height;
  auto;
  background-image: url('http://dummyimage.com/1000x400/b895b8/fff.jpg&text=+');
  background-size: cover;
}
.banner_title {
  background: rgba(0, 0, 0, 0.7) none repeat scroll 0 0;
  color: #fff;
  display: inline-block;
}
.banner_title > div {
  padding: 15px;
}
&#13;
<div class="box">
  <div class="banner">
    <div class="banner_content">
      <div class="banner_title">
        THIS MESSAGE IS A TEST MESSAGE
      </div>
      <div>
        <button>
          This is a test button
        </button>
      </div>
    </div>
  </div>
</div>
&#13;
&#13;
&#13;

https://jsfiddle.net/j90gaawb/6/

答案 2 :(得分:1)

尝试以下CSS:

.banner {
    position: relative;
}

.box {
    left: 0;
    position: absolute;
    text-align: center;
    top: 30px;
    width: 100%;
}