垂直居中的内容:before /:after伪元素 [英] Vertically centering content of :before/:after pseudo-elements

查看:3602
本文介绍了垂直居中的内容:before /:after伪元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想尝试类似这张图片:





我有一个包裹在div中的图片(作为幻灯片的一部分)元素,我显示两个控件移动到幻灯片的下一个(>>)或上一个(<<)图像。



到目前为止,

  div {
position:relative;
}

div:before {
display:block;
height:100%;
content:stuff;
position:absolute;
top:0; left:0;
text-align:center;
}

然而,我不能将伪元素的内容文本如下所示:





这是否可以实现?如果没有,什么是最语义的解决方法?
我不想让元素本身居中,只是它的内容。

编辑 http://jsfiddle.net/rdy4u/



编辑2: ,img是液体/流体,div / img的高度未知,宽度设置为800px, max-width 到80%。

解决方案

假设你的元素不是< img> 允许自我关闭的元素),让我们假设它是一个< div> ,所以一种方法可以是:

  div {
height:100px;
line-height:100px;
}
div:before,div:after {
content:;
...
display:inline-block;
vertical-align:middle;
height:...;
line-height:normal;
}

如果不能更改div的行高,另一种方法是:

  div {
position:relative;
}
div:before,div:after {
position:absolute;
display:block;
top:50%;
-webkit-transform:translateY(-50%);
-moz-transform:translateY(-50%);
-ms-transform:translateY(-50%);
transform:translateY(-50%);
content:;
width:...
}

否则,中心位置的背景。


I'm trying to achieve something similar to this picture:

I have an image (as part of a slideshow) wrapped in a div, and with :before and :after pseudo-elements, I display two controls to move onto the next (>>) or previous (<<) images of the slideshow.

So far, I have this:

div {
  position: relative;
}

div:before {
  display:block;
  height: 100%;
  content: "stuff";
  position:absolute;
  top: 0; left: 0;
  text-align: center;
}

I can't, however, center the content of the pseudo-elements, the text appears like this:

Is this possible to achieve? If not, what would be the most semantic workaround? I do not want to center the element itself, only its content. I'd prefer to have the element stretched to 100% height.

Edit: http://jsfiddle.net/rdy4u/

Edit2: Also, the img is liquid/fluid, the height of the div/img are unknown, and the width is set to 800px and max-width to 80%.

解决方案

Assuming your element is not an <img> (because pseudo elements are not allowed on self-closing elements), let's suppose it's a <div>, so a way could be:

div {
    height: 100px ;
    line-height: 100px;
}
div:before, div:after {
    content: "";
    ...
    display: inline-block;
    vertical-align: middle;
    height: ...;
    line-height: normal;
}

If you cannot change the line-height of the div, another way is:

div {
    position: relative;
}
div:before, div:after {
    position: absolute;
    display: block;
    top: 50%;
    -webkit-transform: translateY(-50%);
    -moz-transform: translateY(-50%);
    -ms-transform: translateY(-50%);
    transform: translateY(-50%);
    content: "";
    width: ...
}

Otherwise, just place the indicators as a background in center position.

这篇关于垂直居中的内容:before /:after伪元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆