Open In App

How to make Elements Float to Center?

Last Updated : 17 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

We have an element in the HTML document and we will float the elements to the center using CSS.

The CSS float property is used to set or return the horizontal alignment of elements. But this property allows an element to float only right or left side of the parent body with the rest of the elements wrapped around it.

We will use the CSS display property to achieve this.

Example 1: This example set the position of elements exactly at the center of the screen. 

html
<!DOCTYPE html>
<html>

<head>
    <title>
        Make float to center to element
    </title>
    
    <!-- Style to set element float
        to center -->
    <style>
        .Center {
            width:200px;
            height:200px;
            position: fixed;
            background-color: blue;
            top: 50%;
            left: 50%;
            margin-top: -100px;
            margin-left: -100px;
        }
    </style>
</head>

<body>
    <div class="Center"></div>
</body>

</html>                    

Output: Example 2: This example set the position of text float elements exactly at the center of the screen. 

html
<!DOCTYPE html>
<html>

<head>
    
    <!-- Style to set text-element
        to center -->
    <style>
        .center {
            text-align-last: center;
            border: 2px solid black;
        }
    </style>
</head>

<body>
    <h2 style = "text-align:center">
        Text is centered:
    </h2>
    
    <div class="center">
        <p>
            <font color="green">
                GeeksForGeeks A Computer
                Science Portal for Geeks
            </font>
        </p>
    </div>
</body>

</html>                    

Output:

CSS is the foundation of webpages, is used for webpage development by styling websites and web apps. You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples.


Next Article

Similar Reads