How to achieve vertical and horizontal centering in css when the size of the element is not known (code)

不言
Release: 2018-08-09 17:11:47
Original
2603 people have browsed it

The content of this article is about how to achieve vertical and horizontal centering (code) of elements of unknown size in CSS. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Idea: Position the child elements absolutely, 50% from the top, 50% from the left, and then use css3 transform:translate(-50%; -50%)
Advantages: High-end, can be used in the webkit kernel Using
in the browser Disadvantages: The transform attribute is not supported under IE9

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>未知宽高元素水平垂直居中</title>
</head>
<style>
.parent3{
    position: relative;
    height:300px;
    width: 300px;
    background: #FD0C70;
}
.parent3 .child{
    position: absolute;
    top: 50%;
    left: 50%;
    color: #fff;
    transform: translate(-50%, -50%);
}
</style>
<body>
<p class="parent3">
        <p class="child">hello world-3</p>
    </p>
</body>
</html>
Copy after login

Related recommendations:

Code examples of CSS selectors and code examples of css priority

When there are too many words on the page, how to use css to make the excess part display ellipses? (Single/multi-line code demonstration)

The above is the detailed content of How to achieve vertical and horizontal centering in css when the size of the element is not known (code). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template