Home >Web Front-end >CSS Tutorial >How to set a div to be horizontally centered with CSS
How to set the horizontal centering of divs with CSS: 1. Set the "margin: 0 auto" style to the div element; 2. Set the "text-align: center" style in the parent div element, at the child level Set the "display: inline-block" style in the div element.
The operating environment of this tutorial: Windows7 system, CSS3&&HTML5 version, Dell G3 computer.
Method: Element binding attributes: margin: 0 auto;
<div class="div-parent"> <style> .div-parent { width: 400px; height: 200px; background-color: #aaa; } .div-child { width: 100px; height: 50px; background-color: #007FFF; margin: 0 auto; } </style> <div class="div-child"></div> </div>
Effect:
Note: Commonly used, suitable for known parent element width Situation
Method:Parent element setting attribute:text-align: center;
Set attributes for sub-level elements: display: inline-block;
<div class="div-parent"> <style> .div-parent { width: 400px; height: 200px; background-color: #aaa; text-align: center; } .div-child { width: 100px; height: 50px; background-color: #007FFF; display: inline-block; } </style> <div class="div-child"></div> </div>
The effect is as shown:
Note: Inline-block has browser compatibility issues, and the side effects caused by setting inline-block will be dealt with separately.
Method:Parent element setting attribute:position: relative;
##1 -level element setting attributes: posity: absolute;
<div class="div-parent"> <style> .div-parent { width: 400px; height: 200px; background-color: #aaa; position: relative; } .div-child { width: 80px; height: 50px; background-color: #007FFF; position:absolute; left: 40%; } </style> <div class="div-child"></div> </div>
effect As shown
Applicable to situations where the width of the parent element is known. It is troublesome to set the center positioning yourself.
【Recommended learning:css video tutorial】
The above is the detailed content of How to set a div to be horizontally centered with CSS. For more information, please follow other related articles on the PHP Chinese website!