Home >Web Front-end >CSS Tutorial >How to set alignment in css
Setting method: 1. Use the "margin:0px auto" statement to set the horizontal alignment; 2. Use the position attribute and the top, bottom, left and right attributes to set the left or right alignment; 3. Use "float: right|left" statement sets left or right alignment.
The operating environment of this tutorial: Windows 7 system, CSS3&&HTML5 version, Dell G3 computer.
1. Use the margin attribute to align elements horizontally
You can align elements by setting the left and right margins to "auto". But the premise is that it must be stated! DOCTYPE, otherwise it is invalid in IE8. This will allow you to center the element, for example:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>document</title> <style> div{ margin: 0px auto; width: 70%; height: 300px; background-color: red; } </style> </head> <body> <div></div> </body> </html>
Tip: If the width is 100%, the alignment has no effect.
2. Use the position attribute for left and right alignment
Using this method is undoubtedly the best method in terms of compatibility, but when using the position attribute, please always set it! DOCTYPE statement, there is a problem in IE8 and earlier versions. If the container element (
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>document</title> <style> body{ margin: 0; padding: 0; } .container{ position: relative; width: 100%; } .right{ position: absolute; right: 0px; width: 300px; height: 50px; background-color: red; } </style> </head> <body> <div class="container"> <div class="right"></div> </div> </body> </html>
3. Use the float attribute for left and right alignment
There is a problem in IE8 and earlier versions when using the float attribute. If the !DOCTYPE declaration is omitted, IE8 and earlier will add 17px of margin to the right. This appears to be space reserved for the scrollbar. When using the float attribute, always set the !DOCTYPE declaration: For example:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>document</title> <style> body{ margin: 0; padding: 0; } .right{ float: right; width: 300px; height: 50px; background-color: red; } </style> </head> <body> <div class="container"> <div class="right"></div> </div> </body> </html>
Recommended learning: css video tutorial
The above is the detailed content of How to set alignment in css. For more information, please follow other related articles on the PHP Chinese website!