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

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

问题描述

我正在尝试实现类似于这张图片的效果:

我有一个包含在 div 中的图像(作为幻灯片的一部分),并且使用 :before 和 :after 伪元素,我显示了两个控件以移动到下一个 (>>) 或上一个 (<<) 幻灯片的图像.

到目前为止,我有这个:

div {位置:相对;}div:之前{显示:块;高度:100%;内容:东西";位置:绝对;顶部:0;左:0;文本对齐:居中;}

但是,我不能将伪元素的内容居中,文本显示如下:

这有可能实现吗?如果不是,最语义化的解决方法是什么?我不想将元素本身居中,而只是将其内容居中.我希望将元素拉伸到 100% 的高度.

http://jsfiddle.net/rdy4u/p>

Edit2:另外,img是liquid/fluid,div/img的高度未知,宽度设置为800px,max-width为80%.

解决方案

假设你的元素不是 <img> (因为自闭合元素上不允许使用伪元素),让我们假设它是一个 <div>,所以一种方法可能是:

div {高度:100 像素;行高:100px;}div:之前,div:之后{内容: "";...显示:内联块;垂直对齐:中间;高度: ...;行高:正常;}

如果你不能改变 div 的 line-height,另一种方法是:

div {位置:相对;}div:之前,div:之后{位置:绝对;显示:块;最高:50%;-webkit-transform: translateY(-50%);-moz 变换:翻译 Y(-50%);-ms-transform: translateY(-50%);变换:translateY(-50%);内容: "";宽度: ...}

否则,只需将指示器作为背景放置在中心位置.

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天全站免登陆