##(1) Inline elements (text, Pictures, inline tags (Methods to horizontally center an element: 1. For inline elements, you can use the "text-align: center;" attribute to achieve horizontal centering; 2. For block-level elements, you can use the "margin: 0 auto" attribute to achieve horizontal centering. Centered; 3. Implemented through flex, set the main axis direction to be centered.
span), inline block tags (
display: inline-block)):
text-align: center, below with
span For example:
<p class="father"> <!-- 行内元素 --> <span class="son">hello</span> </p>
.father { width: 200px; height: 200px; border: 1px solid red; text-align: center;}
text-alignhas inheritance and will affect descendant elements
margin: 0 auto
<!-- 相对于body居中 --><body> <!-- 块级元素 --> <p class="son"></p></body>
.son { width: 200px; height: 200px; border: 1px solid red; margin: 0 auto;}
flex Implementation, set the main axis direction to be centered
<p class="father"> <span class="son"></span> </p>
.father { width: 500px; height: 100px; border: 1px solid red; display: flex; justify-content: center;}.son { width: 100px; background-color: turquoise;}
justify-content: space-around; /* 子元素左右两边距离均匀分布 */或justify-content: space-between; /* 最左边和最右边元素靠紧父元素,其余均匀 */
IE10 and above support
<p class="father"> <span class="son"></span> </p>
.father { width: 500px; height: 100px; border: 1px solid red; position: relative; } .son { position: absolute; width: 100px; height: 100px; background-color: red; left: 50%; transform: translate(-50%);/* margin-left: -50% */ }
margin-leftBetter compatibility
IE9 and above support
transform, and you need to know the width value.
The above is the detailed content of How to center an element horizontally. For more information, please follow other related articles on the PHP Chinese website!