Example code for horizontal centering of css+div

零下一度
Release: 2017-06-24 11:45:28
Original
1879 people have browsed it

Achieve horizontal centering of div content

Implementation plan one: margin:0 auto;

div{
     height:100px;
     width:100px;
     background:red;
     margin:0 auto;
  }
Copy after login

 

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>div水平居中</title>
	</head>
	<body>
		<div></div>
	</body>
</html>
Copy after login

 

Solution 2 to achieve horizontal centering of div: position: absolute; absolute positioning

##
div{height:100px;width:100px;background:red;position:absolute;
   left:50%;
   right:50%;
   margin: auto;
}
Copy after login
Achieve horizontal and vertical centering of div

Implementation plan one: position: fixed; fixed positioning

div{height:100px;width:100px;background:red;position:fixed;left:0;top:0;bottom:0;right:0;margin:auto;
            }
Copy after login
Implementation plan two: position:absolute;absolute positioning

div{height:100px;width:100px;background:red;position:absolute;left:0;top:0;bottom:0;right:0;margin:auto;
            }
Copy after login

Implementation plan two: css3+position;

div{height:100px;width:100px;background:red;position:absolute;left:50%;top:50%;transform:translate(-50%,-50%);
            }
Copy after login
Transform is a new attribute of css3, so it needs to be prefixed to be compatible with mobile phones and other browsers device. Such as

-ms-transform:translate(-50%,-50%); /* IE 9 */-moz-transform:translate(-50%,-50%); /* Firefox */-webkit-transform:translate(-50%,-50%);/* Safari and Chrome */-o-transform:translate(-50%,-50%); /* Opera */
Copy after login

The above is the detailed content of Example code for horizontal centering of css+div. 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 Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template