Home > Article > Web Front-end > How to Make a Div Expand from Its Center Using CSS?
When we expand a div using CSS, it typically expands from its top-left corner, leaving the center untouched. However, there might be scenarios where we want the expansion to originate from the center of the div. With creative CSS techniques, we can achieve this effect, as discussed below.
To expand the div from the center, the key lies in transitioning the margin. A formula is employed to adjust the margin, ensuring that the expansion occurs symmetrically around the center point.
This option expands the div within the reserved space around it:
<code class="css">#square { margin: 100px; transition: width 1s, height 1s, margin 1s; ... } #square:hover { margin: 55px; }</code>
Here, the div expands over the surrounding elements:
<code class="css">#square { margin: 0; /*for centering purposes*/ transition: width 1s, height 1s, margin 1s; ... } #square:hover { margin: -50px; /* 0 - (110px - 10px [= 100px]) / 2 = -50px */ }</code>
This option expands the div over elements before it in the flow and shifts elements after it:
<code class="css">#square { position: relative; transition: width 1s, height 1s, top 1s, left 1s, margin 1s; ... } #square:hover { top: -50px; left: -50px; margin-right: -50px; margin-bottom: -50px; }</code>
The provided solution works best for square elements. For non-square elements, the transition needs to adjust differently for each direction. As an example, we can adjust the width twice as much as the height:
<code class="css">#rectangle { transition: width 1s, height 1s, margin 1s; ... } #rectangle:hover { margin: -50px -100px; /* margin: -50px -((initial margin - width change (or height change))/2) */ }</code>
By following these techniques, we can achieve the desired effect of expanding a div from its center, without resorting to JavaScript.
The above is the detailed content of How to Make a Div Expand from Its Center Using CSS?. For more information, please follow other related articles on the PHP Chinese website!