ADVERTISEMENT
ADVERTISEMENT

How do I center floated elements using CSS?

Learn, how to center floated elements using CSS?
Submitted by Apurva Mathur, on June 19, 2022

CSS float Property: The float property defines the location of the HTML element. It basically shifts the element to the right side or the left side (According to the preference).

float property values:

  • None
  • Left
  • Right
  • Initial
  • Inherit

Among all these values none of the values center the floated elements so we have to apply the custom CSS.

Example:

<!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>

Output:

Example: Center floated elements using CSS

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 Tutorial & Examples »


ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.