1 Preface
When doing page layout, it is often necessary to center some page elements. Of course, you can set the top and left of the element to center it, but when the size of the parent container changes, you have to modify the top and left of the child element to keep it centered; when the user's monitor resolution is different from yours Different test machines may cause the interface to be messy. Therefore, this method of setting fixed values is obviously clumsy from the perspective of the ease of maintenance of the code or the adaptability to displays with different resolutions. Therefore, when doing page layout, you should try to minimize the use of fixed value layout methods. Here are several ways to center page elements.
1Div centeredSet text-align:center in the parent window. It should be noted that this method only works for inline elements, so it must be in a centered div Set display:inline-block. The red line in the following code shows how to center three divs in the itemContainer.
If you want to center a single element, you can also use margin:0auto, but this method cannot center multiple elements in the parent window.
The text-align attribute can only set the left and right centering. The following methods can be used for top and bottom centering: top:50%;margin-top:-40px. top:50% sets the top of the div to be 50% of the height of the parent container, but the div itself has a height. Margin-top:-40px means moving up half of the height of the div itself. It should be noted that the parent container must set overflow:auto, otherwise the above settings will affect the size of the parent container.
If you need to center up, down, left, and right at the same time, use it in conjunction with the method shown in 2.1.
The red line in the following code shows how to center the itemContainer in the entire page.
2 Text centeringMethod 1: Place the text in the div tag, and then set the center according to the div centering method
Method 2: Center left and right text-align:center , top and bottom centering can be set by setting line-height in the parent container of the text equal to the height of the parent container, as shown in the following code.
3. Center the background imageSet background: 50% 50%. You can adjust these two parameters to center only up and down (background: 0% 50%) and center left and right (background: 50 % 0%).
4 test cases<%@page contentType="text/html;charset=UTF-8"pageEncoding="UTF-8"%>
< ;!DOCTYPEhtml PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN""http://www.w3.org/TR/html4/loose.dtd">
.item{ background:url("pic.png")no-repeat 50% 50%;position:relative;display:inline-block;width:80px;height:80px;outline:solid2px #000000;;line-height:80px}
style="position:relative;width:400px;height:80px;outline:solid 2px#ff0000; text-align:center;top:50%;margin:0 auto;margin-top:-40px">
>
;div class="item">Test
& lt;/body>