Introduction to the method of using CSS to center floating elements

高洛峰
Release: 2017-03-10 11:02:14
Original
1958 people have browsed it

This article mainly introduces the method of using CSS to center floating elements. It is the basic knowledge for introductory learning of CSS. Friends in need can refer to it

Method 1

Set the floating mode of the container to absolute positioning
Then determine the width and height of the container, such as the layer with a width of 500 and a height of 300
Then set the margins of the layer

 p{   
        width:500px;   
        height:300px;   
        margin:-150px 0 0 -250px;   
        position:absolute;   
        left:50%;   
        top:50%;   
        background-color:#000;   
}
Copy after login


Method 2

The parent element and the child element float to the left at the same time, then the parent element moves 50% relative to the left, and then the child element moves 50% relative to the right, or the child element moves relative to the left - 50% is fine.

<!DOCTYPE html><html><head>   
    <title>Demo</title>   
    <meta charset="utf-8"/>   
    <style type="text/css">   
        .p{   
            position:relative;   
            left:50%;   
            float:left;   
        }   
        .c{   
            position:relative;   
            float:left;   
            rightright:50%;   
        }   
    </style></head><body>   
    <p class="p">   
        <h1 class="c">Test Float Element Center</h1>   
    </p>   
</body>   
</html>
Copy after login


The above is the detailed content of Introduction to the method of using CSS to center floating elements. 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!