Core points
- Centing in CSS, especially vertical centering, can be tricky. Sass can encapsulate various CSS centering methods into an easy-to-use mixin.
- The centering method depends on whether the element size is known. If unknown, use CSS transformation for increased flexibility; if known, use negative margins. The Sass mixin positions the upper left corner of the element in the middle of the container and moves it backwards half of its width and height.
- Mixin can be further improved by including
@supports
rules to check CSS conversion support, or by performing stricter checks on parameters to ensure they are valid values ??of width and height. - Flexbox is another solution to center an element in its parent element. It is easier to use if conditions permit. Flexbox centers child elements by setting three attributes on the parent element.
Centering CSS has always been a tedious task and has even become a joke in the language, leading to jokes like "We successfully sent astronauts to the moon, but we can't align vertically in CSS" .
While CSS is indeed a bit tricky when dealing with centering, especially vertically centering, I think these jokes are a bit unfair. Actually, there are many ways to center content in CSS, you just need to know how to do it.
This article is not intended to explain how these methods work, but to illustrate how they are encapsulated in Sass mixin for ease of use. So if you feel a little uncomfortable with CSS centering, I suggest you read some resources in advance:
- How to center in CSS
- CSS Centered: Complete Guide
Are you ready? Let's get started.
Overview
First, we will focus on centering the element in its parent element, as this is the most common use case for absolute centering (modal boxes, parts, etc.). When you ask someone about CSS centering, the usual responses you get are: Do you know the size of the element? The reason is that if you don't know the element size, the best solution is to rely on CSS conversion. This will slightly reduce browser support, but it is very flexible. If you can't use CSS conversion or know the width and height of an element, it's easy to rely on negative margins.
So our mixin will basically do the following: position the upper left corner of the element absolutely in the middle of the container, and then move it backwards with a CSS conversion or negative margin depending on whether the size is passed to the mixin or not, move it backwards its width using CSS conversion or negative margins depending on whether the size is passed to the mixin. and half of height. No size: Use conversion; with size: Use margins.
Then you can use it like this:
<code>/** * 為子元素啟用位置上下文 */ .parent { position: relative; } /** * 將元素在其父元素中絕對居中 * 沒有將尺寸傳遞給mixin,因此它依賴于CSS轉(zhuǎn)換 */ .child-with-unknown-dimensions { @include center; } /** * 將元素在其父元素中絕對居中 * 將寬度傳遞給mixin,因此我們對水平軸使用負邊距,對垂直軸使用CSS轉(zhuǎn)換 */ .child-with-known-width { @include center(400px); } /** * 將元素在其父元素中絕對居中 * 將高度傳遞給mixin,因此我們對垂直軸使用負邊距,對水平軸使用CSS轉(zhuǎn)換 */ .child-with-known-height { @include center($height: 400px); } /** * 將元素在其父元素中絕對居中 * 將寬度傳遞給mixin,因此我們對水平軸和垂直軸都使用負邊距 */ .child-with-known-dimensions { @include center(400px, 400px); }</code>
After compilation, it should output the following:
<code>.parent { position: relative; } .child-with-unknown-dimensions { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); } .child-with-known-width { position: absolute; top: 50%; left: 50%; margin-left: -200px; width: 400px; transform: translateY(-50%); } .child-with-known-height { position: absolute; top: 50%; left: 50%; transform: translateX(-50%); margin-top: -200px; height: 400px; } .child-with-known-dimensions { position: absolute; top: 50%; left: 50%; margin-left: -200px; width: 400px; margin-top: -200px; height: 400px; }</code>
OK, this looks a bit verbose, but remember that this output is for demonstration purposes only. In a given case, it is unlikely that you will find yourself using all of these methods at the same time.
Build mixin
Okay, let's dig deeper. From the previous code snippet, we already know the signature of mixin: it has two optional parameters, $width
and $height
.
<code>/** * 為子元素啟用位置上下文 */ .parent { position: relative; } /** * 將元素在其父元素中絕對居中 * 沒有將尺寸傳遞給mixin,因此它依賴于CSS轉(zhuǎn)換 */ .child-with-unknown-dimensions { @include center; } /** * 將元素在其父元素中絕對居中 * 將寬度傳遞給mixin,因此我們對水平軸使用負邊距,對垂直軸使用CSS轉(zhuǎn)換 */ .child-with-known-width { @include center(400px); } /** * 將元素在其父元素中絕對居中 * 將高度傳遞給mixin,因此我們對垂直軸使用負邊距,對水平軸使用CSS轉(zhuǎn)換 */ .child-with-known-height { @include center($height: 400px); } /** * 將元素在其父元素中絕對居中 * 將寬度傳遞給mixin,因此我們對水平軸和垂直軸都使用負邊距 */ .child-with-known-dimensions { @include center(400px, 400px); }</code>
Continue. In any case, mixin requires absolute positioning of elements, so we can start from this point.
<code>.parent { position: relative; } .child-with-unknown-dimensions { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); } .child-with-known-width { position: absolute; top: 50%; left: 50%; margin-left: -200px; width: 400px; transform: translateY(-50%); } .child-with-known-height { position: absolute; top: 50%; left: 50%; transform: translateX(-50%); margin-top: -200px; height: 400px; } .child-with-known-dimensions { position: absolute; top: 50%; left: 50%; margin-left: -200px; width: 400px; margin-top: -200px; height: 400px; }</code>
We will have to write the code cleverly. Let's pause here and analyze the different options we have:
寬度 | 高度 | 解決方案 |
---|---|---|
未定義 | 未定義 | translate |
定義 | 定義 | margin |
定義 | 未定義 | margin-left translateY |
未定義 | 定義 | translateX margin-top |
Let's use this.
<code>/** * 為子元素啟用位置上下文 */ .parent { position: relative; } /** * 將元素在其父元素中絕對居中 * 沒有將尺寸傳遞給mixin,因此它依賴于CSS轉(zhuǎn)換 */ .child-with-unknown-dimensions { @include center; } /** * 將元素在其父元素中絕對居中 * 將寬度傳遞給mixin,因此我們對水平軸使用負邊距,對垂直軸使用CSS轉(zhuǎn)換 */ .child-with-known-width { @include center(400px); } /** * 將元素在其父元素中絕對居中 * 將高度傳遞給mixin,因此我們對垂直軸使用負邊距,對水平軸使用CSS轉(zhuǎn)換 */ .child-with-known-height { @include center($height: 400px); } /** * 將元素在其父元素中絕對居中 * 將寬度傳遞給mixin,因此我們對水平軸和垂直軸都使用負邊距 */ .child-with-known-dimensions { @include center(400px, 400px); }</code>
Now that we have set up the framework for mixin, we just need to fill in the gaps with the actual CSS declaration.
<code>.parent { position: relative; } .child-with-unknown-dimensions { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); } .child-with-known-width { position: absolute; top: 50%; left: 50%; margin-left: -200px; width: 400px; transform: translateY(-50%); } .child-with-known-height { position: absolute; top: 50%; left: 50%; transform: translateX(-50%); margin-top: -200px; height: 400px; } .child-with-known-dimensions { position: absolute; top: 50%; left: 50%; margin-left: -200px; width: 400px; margin-top: -200px; height: 400px; }</code>
Note: #{0 0}
Skill is a not-so-clean technique used to prevent Sass from performing slightly overly aggressive compression, which can cause margin: mt 0 ml
rather than margin: mt 0 0 ml
Go a step further
We can do several things to further improve our mixin, such as including a rule in the mixin to check CSS conversion support, or assume that Modernizr exists (or allows) and outputs conditional styles based on whether CSS conversion is supported or not . We can also perform stricter checks on parameters to ensure they are valid values ??of width and height. @supports
How about Flexbox?
I'm pretty sure some of you are jumping in the seat, thinking about how we can use Flexbox to center an element in its parent element. Indeed, this is possible, and it turns out that if conditions permit, this is the easiest of all solutions.The main difference between the solution we just set up and the Flexbox solution is that the latter is built on the parent element, while the former focuses on the child element (provided that any of its ancestors are positioned differently than static).
In order for an element to center its child elements, you only need to set three properties. You can create a mixin, placeholder, class, or any element you like for this.
<code>/// 在其父元素中水平、垂直或絕對居中元素 /// 如果指定,此mixin將根據(jù)元素的尺寸使用負邊距。否則,它將依賴于CSS轉(zhuǎn)換,CSS轉(zhuǎn)換的瀏覽器支持度較低,但由于它們與尺寸無關(guān),因此更靈活。 /// /// @author Kitty Giraudel /// /// @param {Length | null} $width [null] - 元素寬度 /// @param {Length | null} $height [null] - 元素高度 /// @mixin center($width: null, $height: null) { .. }</code>Assuming you have added the relevant vendor prefix (via mixin or Autoprefixer), this solution should "work properly" in many browsers.
<code>@mixin center($width: null, $height: null) { position: absolute; top: 50%; left: 50%; // 更多魔法在這里... }</code>As you must have guessed, it produces:
<code>@mixin center($width: null, $height: null) { position: absolute; top: 50%; left: 50%; @if not $width and not $height { // 使用 `translate` } @else if $width and $height { // 使用 `margin` } @else if not $height { // 使用 `margin-left` 和 `translateY` } @else { // 使用 `margin-top` 和 `translateX` } }</code>
Final Thoughts
We want a short mixin to easily center the element in its parent; this mixin does the job and does a good job. Not only is it smart enough to work regardless of whether the element has a specific size or not, it also provides a friendly and intuitive API, which is very important.By looking at the code, anyone can immediately understand that the
line is containing a helper function that performs some logic to center the element in its parent element. But remember that in order for this method to work, the latter (or any parent element in the DOM tree) must have a different position than static! ;)@include center
http://www.miracleart.cn/link/780bc6caf343bb06a4372c0821012624.
(Due to space limitations, the FAQs part is omitted here. The content of the FAQs part is highly duplicated from the article content, and can be added or modified by yourself as needed.)
The above is the detailed content of Centering With Sass. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

There are three ways to create a CSS loading rotator: 1. Use the basic rotator of borders to achieve simple animation through HTML and CSS; 2. Use a custom rotator of multiple points to achieve the jump effect through different delay times; 3. Add a rotator in the button and switch classes through JavaScript to display the loading status. Each approach emphasizes the importance of design details such as color, size, accessibility and performance optimization to enhance the user experience.

To deal with CSS browser compatibility and prefix issues, you need to understand the differences in browser support and use vendor prefixes reasonably. 1. Understand common problems such as Flexbox and Grid support, position:sticky invalid, and animation performance is different; 2. Check CanIuse confirmation feature support status; 3. Correctly use -webkit-, -moz-, -ms-, -o- and other manufacturer prefixes; 4. It is recommended to use Autoprefixer to automatically add prefixes; 5. Install PostCSS and configure browserslist to specify the target browser; 6. Automatically handle compatibility during construction; 7. Modernizr detection features can be used for old projects; 8. No need to pursue consistency of all browsers,

Themaindifferencesbetweendisplay:inline,block,andinline-blockinHTML/CSSarelayoutbehavior,spaceusage,andstylingcontrol.1.Inlineelementsflowwithtext,don’tstartonnewlines,ignorewidth/height,andonlyapplyhorizontalpadding/margins—idealforinlinetextstyling

Setting the style of links you have visited can improve the user experience, especially in content-intensive websites to help users navigate better. 1. Use CSS's: visited pseudo-class to define the style of the visited link, such as color changes; 2. Note that the browser only allows modification of some attributes due to privacy restrictions; 3. The color selection should be coordinated with the overall style to avoid abruptness; 4. The mobile terminal may not display this effect, and it is recommended to combine it with other visual prompts such as icon auxiliary logos.

Use the clip-path attribute of CSS to crop elements into custom shapes, such as triangles, circular notches, polygons, etc., without relying on pictures or SVGs. Its advantages include: 1. Supports a variety of basic shapes such as circle, ellipse, polygon, etc.; 2. Responsive adjustment and adaptable to mobile terminals; 3. Easy to animation, and can be combined with hover or JavaScript to achieve dynamic effects; 4. It does not affect the layout flow, and only crops the display area. Common usages are such as circular clip-path:circle (50pxatcenter) and triangle clip-path:polygon (50%0%, 100 0%, 0 0%). Notice

To create responsive images using CSS, it can be mainly achieved through the following methods: 1. Use max-width:100% and height:auto to allow the image to adapt to the container width while maintaining the proportion; 2. Use HTML's srcset and sizes attributes to intelligently load the image sources adapted to different screens; 3. Use object-fit and object-position to control image cropping and focus display. Together, these methods ensure that the images are presented clearly and beautifully on different devices.

The choice of CSS units depends on design requirements and responsive requirements. 1.px is used for fixed size, suitable for precise control but lack of elasticity; 2.em is a relative unit, which is easily caused by the influence of the parent element, while rem is more stable based on the root element and is suitable for global scaling; 3.vw/vh is based on the viewport size, suitable for responsive design, but attention should be paid to the performance under extreme screens; 4. When choosing, it should be determined based on whether responsive adjustments, element hierarchy relationships and viewport dependence. Reasonable use can improve layout flexibility and maintenance.

Different browsers have differences in CSS parsing, resulting in inconsistent display effects, mainly including the default style difference, box model calculation method, Flexbox and Grid layout support level, and inconsistent behavior of certain CSS attributes. 1. The default style processing is inconsistent. The solution is to use CSSReset or Normalize.css to unify the initial style; 2. The box model calculation method of the old version of IE is different. It is recommended to use box-sizing:border-box in a unified manner; 3. Flexbox and Grid perform differently in edge cases or in old versions. More tests and use Autoprefixer; 4. Some CSS attribute behaviors are inconsistent. CanIuse must be consulted and downgraded.
