Home > Article > Web Front-end > css div vertical and horizontal centering implementation_html/css_WEB-ITnose
For example, if you set the div below in HTML to be centered vertically and horizontally, then
<<strong>div </strong><strong>id=</strong><strong>"box"</strong>></<strong>div</strong>>
css Style
<strong>#box</strong>{ <strong>width</strong>: 300<strong>px</strong>; <strong>height</strong>: 200<strong>px</strong>; <strong>margin-left</strong>: -150<strong>px</strong>;//宽度的一半,很重要,不然不居中,会偏右 <strong>margin-top</strong>: -100<strong>px</strong>;//高度的一半 <strong>position</strong>: <strong>absolute</strong>;//绝对定位方式 <strong>top</strong>: 50%; <strong>left</strong>: 50%; <strong>background-color</strong>: <strong>aqua</strong>;//背景颜色,便于测试查看效果}