Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.7k views
in Technique[技术] by (71.8m points)

css - Vertically centering content of :before/:after pseudo-elements

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

enter image description here

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:

enter image description here

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%.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...