Vertically center elements in CSS

前端 未结 5 1263
醉酒成梦
醉酒成梦 2020-12-03 23:05

I have two elements side-by-side. Element 2 is smaller than Element 1. Both elements do not have a fixed height. I need to vertically center Element 2. How do I achieve

5条回答
  •  星月不相逢
    2020-12-03 23:45

    Not easily. Some popular hacks include using display: table-cell and a parent using display: table (I don't remember if the valign="center" attribute is needed), or using absolute positioning with top: 45% or so (not precise, but OK for small elements).

    To determine the best method, we need to know more about your layout. What are they centered within? Will/can there be a large Y-distance between elements 1 and 2? Does their parent have a fixed height? Do they both have the same parents, or is one a sibling of the other? What method are you using to place them side by side?

    Keep in mind that many tricks require additional hacking to work in IE, and that using Javascript is just cheating and will make your site inaccessible/annoying to people with low vision (who may be using script-unaware screen readers), people with scripts disabled (esp. on mobile or command-line browsers that may not support them well if at all), search engines, etc. It's possible using only CSS (though you may have to add some container elements), but the exact method depends what exactly you're doing.

提交回复
热议问题