中心文本垂直元素更改高度和宽度

时间:2017-02-07 19:24:57

标签: html css

我有以下代码

http://codepen.io/anon/pen/EZeVXG

HTML

<a href="#" class="col-inner">
 <img src="http://placehold.it/450x450" />
 <div class="content">
   <h3>Hello World</h3>
   <p>Lorem Ipsum Dolor Sit Amet</p>
 </div>
</a>

CSS

img{
 max-width: 100%;
 height: auto;
}
.col-inner{
 position: relative;
 display: inline-block;
}
.content{
 position: absolute;
 width: 90%;
 height: 90%;
 top: 5%;
 left: 5%;
 background-color: rgba(0,0,0,.7);
 color: #FFF;
 text-align: center;
}

我尝试过在Stack Overflow上发现的一系列技术,但只有当你知道宽度和高度时,一切似乎都有效。在弹出浏览器时,这两个属性都会发生变化。有没有办法让文字在整个方向上保持垂直居中?

2 个答案:

答案 0 :(得分:2)

我在stackoverflow上也发现了这个技巧,我会在找到它后立即添加一个链接:

height: auto; // (this is the default)
position: absolute;
top: 50%;
transform: translateY(-50%);

这是有效的,因为translateY取得了元素的高度,top使用了周围元素的高度。

http://codepen.io/anon/pen/zNJvgg

答案 1 :(得分:0)

您应该尝试使用flexbox,如果可能,请在您的HTML中进行一些更改。

在我看来,为了完成这项工作,我会使用:

HTML

<a href="#" class="col-inner">
  <div class="content">
    <h3>Hello World</h3>
    <p>Lorem Ipsum Dolor Sit Amet</p>
  </div>
</a>

CSS

    .col-inner{
  max-width: 100%;
  min-height: 150px;
  position: relative;
  background-image: url('http://placehold.it/450x450');
  background-repeat: no-repeat;
  background-size: cover;
  background-position: 50% 50%;
  display: flex;
  justify-content:center;
  align-items:center;
}
.content{
  color: #ff0000;
}

我刚刚将图片添加为background-image作为容器的标记,并将display: flex; justify-content:center; align-items:center用于水平&amp;将文本和容器内的所有元素垂直居中。

你可以调整height的{​​{1}},看看无论班级有多高,它都会居中。

我已经设置了一个codepen来玩它:code

请注意,如果您想使用.col-inner,则应在代码前加上前缀。使用此网站caniuse查看您应添加到flexbox及相关属性的前缀。

相关问题