Home  >  Article  >  Web Front-end  >  Example code for horizontal centering of css+div

Example code for horizontal centering of css+div

零下一度
零下一度Original
2017-06-24 11:45:281818browse

Achieve horizontal centering of div content

Implementation plan one: margin:0 auto;

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

 

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

 

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;
}
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;
            }
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;
            }

Implementation plan two: css3+position;

div{height:100px;width:100px;background:red;position:absolute;left:50%;top:50%;transform:translate(-50%,-50%);
            }
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 */

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!

Statement:
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