Home > Web Front-end > CSS Tutorial > Use negative margin values ​​​​in CSS to adjust the center position

Use negative margin values ​​​​in CSS to adjust the center position

高洛峰
Release: 2017-02-16 13:39:17
Original
1858 people have browsed it

This is perhaps the most commonly used centering method. If you know the size of each element, set a negative margin value equal to half the width and height (if you do not use the box-sizing: border-box style, you also need to add a padding value), and then match top: 50%; left: 50% ; style will center the block element.

Use negative margin values ​​​​in CSS to adjust the center position

It should be noted that this is the only way to work under IE6-7 as expected.


##CSS CodeCopy content to clipboard

.is-Negative {       
        width: 300px;       
        height: 200px;       
        padding: 20px;       
        position: absolute;       
        top: 50%; left: 50%;       
        margin-left: -170px; /* (width + padding)/2 */      
        margin-top: -120px; /* (height + padding)/2 */      
}
Copy after login


Benefits:

Browser compatibility is very good, even supporting IE6-7

Requires very little coding

Also note:

This is a non-responsive method. You cannot use percentage sizes, nor can you set min-/max-maximum and minimum values.

The content may exceed the container
You need to reserve space for padding, or you need to use the box-sizing: border-box style.

For more related articles about using negative margin values ​​in CSS to adjust the center position, please pay attention to 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 Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template