Home »
CSS
How to make elements float to center using CSS?
In this tutorial, we will learn how to make elements float to center using CSS?
By Apurva Mathur Last updated : July 22, 2023
Answer: Use the CSS position, left, right, and top properties
To make elements float to the center, you can use the CSS position, left, right, and top properties with the specified values. The value should be taken in such a way that element should display at the center of the page. These values can be adjusted based on your requirement where you want to display the float elements. The value of the position property should be fixed.
CSS to make elements float to center
Consider the below-given CSS styes to make elements float to center.
.element {
width: 200px;
height: 100px;
position: fixed;
border: 2px solid red;
right: 40%;
left: 40%;
top: 40%;
}
Example to make elements float to center using CSS
<!DOCTYPE html>
<html>
<head>
<style>
.element {
width:200px;
height:100px;
position: fixed;
border: 2px solid red;
right:40%;
left:40%;
top:40%;
}
p{
text-align: center;
margin-top: 35px;
}
</style>
</head>
<body>
<div class="element">
<p>This is the content</p>
</div>
</body>
</html>
The output of the above example is –
Explanation
Let us first discuss the HTML code then we'll go to styling. So just give some class to div tag (Here, that class name is the "element" you can name it anything.), and inside div tag, I have taken paragraph tag this is because I want my content inside the box.
Now coming to the CSS part, the code starts with setting the width and height of the box, the box in the output is 200px width and 100px height. Make sure to fix the position of the box as it will be set when the body is scrolled up. The values of right-left and top will be set according to the box size if you are increasing the box size then you have to change the values of these properties also. Here all the values are set according to the width of 200px and height of 100px.
To align text in the center, the text-alight=center property is used.
CSS Examples »