1606382501
Skewed Header using HTML & CSS | Pure CSS Effects
#html #css #web-development #developer
1667425440
Perl script converts PDF files to Gerber format
Pdf2Gerb generates Gerber 274X photoplotting and Excellon drill files from PDFs of a PCB. Up to three PDFs are used: the top copper layer, the bottom copper layer (for 2-sided PCBs), and an optional silk screen layer. The PDFs can be created directly from any PDF drawing software, or a PDF print driver can be used to capture the Print output if the drawing software does not directly support output to PDF.
The general workflow is as follows:
Please note that Pdf2Gerb does NOT perform DRC (Design Rule Checks), as these will vary according to individual PCB manufacturer conventions and capabilities. Also note that Pdf2Gerb is not perfect, so the output files must always be checked before submitting them. As of version 1.6, Pdf2Gerb supports most PCB elements, such as round and square pads, round holes, traces, SMD pads, ground planes, no-fill areas, and panelization. However, because it interprets the graphical output of a Print function, there are limitations in what it can recognize (or there may be bugs).
See docs/Pdf2Gerb.pdf for install/setup, config, usage, and other info.
#Pdf2Gerb config settings:
#Put this file in same folder/directory as pdf2gerb.pl itself (global settings),
#or copy to another folder/directory with PDFs if you want PCB-specific settings.
#There is only one user of this file, so we don't need a custom package or namespace.
#NOTE: all constants defined in here will be added to main namespace.
#package pdf2gerb_cfg;
use strict; #trap undef vars (easier debug)
use warnings; #other useful info (easier debug)
##############################################################################################
#configurable settings:
#change values here instead of in main pfg2gerb.pl file
use constant WANT_COLORS => ($^O !~ m/Win/); #ANSI colors no worky on Windows? this must be set < first DebugPrint() call
#just a little warning; set realistic expectations:
#DebugPrint("${\(CYAN)}Pdf2Gerb.pl ${\(VERSION)}, $^O O/S\n${\(YELLOW)}${\(BOLD)}${\(ITALIC)}This is EXPERIMENTAL software. \nGerber files MAY CONTAIN ERRORS. Please CHECK them before fabrication!${\(RESET)}", 0); #if WANT_DEBUG
use constant METRIC => FALSE; #set to TRUE for metric units (only affect final numbers in output files, not internal arithmetic)
use constant APERTURE_LIMIT => 0; #34; #max #apertures to use; generate warnings if too many apertures are used (0 to not check)
use constant DRILL_FMT => '2.4'; #'2.3'; #'2.4' is the default for PCB fab; change to '2.3' for CNC
use constant WANT_DEBUG => 0; #10; #level of debug wanted; higher == more, lower == less, 0 == none
use constant GERBER_DEBUG => 0; #level of debug to include in Gerber file; DON'T USE FOR FABRICATION
use constant WANT_STREAMS => FALSE; #TRUE; #save decompressed streams to files (for debug)
use constant WANT_ALLINPUT => FALSE; #TRUE; #save entire input stream (for debug ONLY)
#DebugPrint(sprintf("${\(CYAN)}DEBUG: stdout %d, gerber %d, want streams? %d, all input? %d, O/S: $^O, Perl: $]${\(RESET)}\n", WANT_DEBUG, GERBER_DEBUG, WANT_STREAMS, WANT_ALLINPUT), 1);
#DebugPrint(sprintf("max int = %d, min int = %d\n", MAXINT, MININT), 1);
#define standard trace and pad sizes to reduce scaling or PDF rendering errors:
#This avoids weird aperture settings and replaces them with more standardized values.
#(I'm not sure how photoplotters handle strange sizes).
#Fewer choices here gives more accurate mapping in the final Gerber files.
#units are in inches
use constant TOOL_SIZES => #add more as desired
(
#round or square pads (> 0) and drills (< 0):
.010, -.001, #tiny pads for SMD; dummy drill size (too small for practical use, but needed so StandardTool will use this entry)
.031, -.014, #used for vias
.041, -.020, #smallest non-filled plated hole
.051, -.025,
.056, -.029, #useful for IC pins
.070, -.033,
.075, -.040, #heavier leads
# .090, -.043, #NOTE: 600 dpi is not high enough resolution to reliably distinguish between .043" and .046", so choose 1 of the 2 here
.100, -.046,
.115, -.052,
.130, -.061,
.140, -.067,
.150, -.079,
.175, -.088,
.190, -.093,
.200, -.100,
.220, -.110,
.160, -.125, #useful for mounting holes
#some additional pad sizes without holes (repeat a previous hole size if you just want the pad size):
.090, -.040, #want a .090 pad option, but use dummy hole size
.065, -.040, #.065 x .065 rect pad
.035, -.040, #.035 x .065 rect pad
#traces:
.001, #too thin for real traces; use only for board outlines
.006, #minimum real trace width; mainly used for text
.008, #mainly used for mid-sized text, not traces
.010, #minimum recommended trace width for low-current signals
.012,
.015, #moderate low-voltage current
.020, #heavier trace for power, ground (even if a lighter one is adequate)
.025,
.030, #heavy-current traces; be careful with these ones!
.040,
.050,
.060,
.080,
.100,
.120,
);
#Areas larger than the values below will be filled with parallel lines:
#This cuts down on the number of aperture sizes used.
#Set to 0 to always use an aperture or drill, regardless of size.
use constant { MAX_APERTURE => max((TOOL_SIZES)) + .004, MAX_DRILL => -min((TOOL_SIZES)) + .004 }; #max aperture and drill sizes (plus a little tolerance)
#DebugPrint(sprintf("using %d standard tool sizes: %s, max aper %.3f, max drill %.3f\n", scalar((TOOL_SIZES)), join(", ", (TOOL_SIZES)), MAX_APERTURE, MAX_DRILL), 1);
#NOTE: Compare the PDF to the original CAD file to check the accuracy of the PDF rendering and parsing!
#for example, the CAD software I used generated the following circles for holes:
#CAD hole size: parsed PDF diameter: error:
# .014 .016 +.002
# .020 .02267 +.00267
# .025 .026 +.001
# .029 .03167 +.00267
# .033 .036 +.003
# .040 .04267 +.00267
#This was usually ~ .002" - .003" too big compared to the hole as displayed in the CAD software.
#To compensate for PDF rendering errors (either during CAD Print function or PDF parsing logic), adjust the values below as needed.
#units are pixels; for example, a value of 2.4 at 600 dpi = .0004 inch, 2 at 600 dpi = .0033"
use constant
{
HOLE_ADJUST => -0.004 * 600, #-2.6, #holes seemed to be slightly oversized (by .002" - .004"), so shrink them a little
RNDPAD_ADJUST => -0.003 * 600, #-2, #-2.4, #round pads seemed to be slightly oversized, so shrink them a little
SQRPAD_ADJUST => +0.001 * 600, #+.5, #square pads are sometimes too small by .00067, so bump them up a little
RECTPAD_ADJUST => 0, #(pixels) rectangular pads seem to be okay? (not tested much)
TRACE_ADJUST => 0, #(pixels) traces seemed to be okay?
REDUCE_TOLERANCE => .001, #(inches) allow this much variation when reducing circles and rects
};
#Also, my CAD's Print function or the PDF print driver I used was a little off for circles, so define some additional adjustment values here:
#Values are added to X/Y coordinates; units are pixels; for example, a value of 1 at 600 dpi would be ~= .002 inch
use constant
{
CIRCLE_ADJUST_MINX => 0,
CIRCLE_ADJUST_MINY => -0.001 * 600, #-1, #circles were a little too high, so nudge them a little lower
CIRCLE_ADJUST_MAXX => +0.001 * 600, #+1, #circles were a little too far to the left, so nudge them a little to the right
CIRCLE_ADJUST_MAXY => 0,
SUBST_CIRCLE_CLIPRECT => FALSE, #generate circle and substitute for clip rects (to compensate for the way some CAD software draws circles)
WANT_CLIPRECT => TRUE, #FALSE, #AI doesn't need clip rect at all? should be on normally?
RECT_COMPLETION => FALSE, #TRUE, #fill in 4th side of rect when 3 sides found
};
#allow .012 clearance around pads for solder mask:
#This value effectively adjusts pad sizes in the TOOL_SIZES list above (only for solder mask layers).
use constant SOLDER_MARGIN => +.012; #units are inches
#line join/cap styles:
use constant
{
CAP_NONE => 0, #butt (none); line is exact length
CAP_ROUND => 1, #round cap/join; line overhangs by a semi-circle at either end
CAP_SQUARE => 2, #square cap/join; line overhangs by a half square on either end
CAP_OVERRIDE => FALSE, #cap style overrides drawing logic
};
#number of elements in each shape type:
use constant
{
RECT_SHAPELEN => 6, #x0, y0, x1, y1, count, "rect" (start, end corners)
LINE_SHAPELEN => 6, #x0, y0, x1, y1, count, "line" (line seg)
CURVE_SHAPELEN => 10, #xstart, ystart, x0, y0, x1, y1, xend, yend, count, "curve" (bezier 2 points)
CIRCLE_SHAPELEN => 5, #x, y, 5, count, "circle" (center + radius)
};
#const my %SHAPELEN =
#Readonly my %SHAPELEN =>
our %SHAPELEN =
(
rect => RECT_SHAPELEN,
line => LINE_SHAPELEN,
curve => CURVE_SHAPELEN,
circle => CIRCLE_SHAPELEN,
);
#panelization:
#This will repeat the entire body the number of times indicated along the X or Y axes (files grow accordingly).
#Display elements that overhang PCB boundary can be squashed or left as-is (typically text or other silk screen markings).
#Set "overhangs" TRUE to allow overhangs, FALSE to truncate them.
#xpad and ypad allow margins to be added around outer edge of panelized PCB.
use constant PANELIZE => {'x' => 1, 'y' => 1, 'xpad' => 0, 'ypad' => 0, 'overhangs' => TRUE}; #number of times to repeat in X and Y directions
# Set this to 1 if you need TurboCAD support.
#$turboCAD = FALSE; #is this still needed as an option?
#CIRCAD pad generation uses an appropriate aperture, then moves it (stroke) "a little" - we use this to find pads and distinguish them from PCB holes.
use constant PAD_STROKE => 0.3; #0.0005 * 600; #units are pixels
#convert very short traces to pads or holes:
use constant TRACE_MINLEN => .001; #units are inches
#use constant ALWAYS_XY => TRUE; #FALSE; #force XY even if X or Y doesn't change; NOTE: needs to be TRUE for all pads to show in FlatCAM and ViewPlot
use constant REMOVE_POLARITY => FALSE; #TRUE; #set to remove subtractive (negative) polarity; NOTE: must be FALSE for ground planes
#PDF uses "points", each point = 1/72 inch
#combined with a PDF scale factor of .12, this gives 600 dpi resolution (1/72 * .12 = 600 dpi)
use constant INCHES_PER_POINT => 1/72; #0.0138888889; #multiply point-size by this to get inches
# The precision used when computing a bezier curve. Higher numbers are more precise but slower (and generate larger files).
#$bezierPrecision = 100;
use constant BEZIER_PRECISION => 36; #100; #use const; reduced for faster rendering (mainly used for silk screen and thermal pads)
# Ground planes and silk screen or larger copper rectangles or circles are filled line-by-line using this resolution.
use constant FILL_WIDTH => .01; #fill at most 0.01 inch at a time
# The max number of characters to read into memory
use constant MAX_BYTES => 10 * M; #bumped up to 10 MB, use const
use constant DUP_DRILL1 => TRUE; #FALSE; #kludge: ViewPlot doesn't load drill files that are too small so duplicate first tool
my $runtime = time(); #Time::HiRes::gettimeofday(); #measure my execution time
print STDERR "Loaded config settings from '${\(__FILE__)}'.\n";
1; #last value must be truthful to indicate successful load
#############################################################################################
#junk/experiment:
#use Package::Constants;
#use Exporter qw(import); #https://perldoc.perl.org/Exporter.html
#my $caller = "pdf2gerb::";
#sub cfg
#{
# my $proto = shift;
# my $class = ref($proto) || $proto;
# my $settings =
# {
# $WANT_DEBUG => 990, #10; #level of debug wanted; higher == more, lower == less, 0 == none
# };
# bless($settings, $class);
# return $settings;
#}
#use constant HELLO => "hi there2"; #"main::HELLO" => "hi there";
#use constant GOODBYE => 14; #"main::GOODBYE" => 12;
#print STDERR "read cfg file\n";
#our @EXPORT_OK = Package::Constants->list(__PACKAGE__); #https://www.perlmonks.org/?node_id=1072691; NOTE: "_OK" skips short/common names
#print STDERR scalar(@EXPORT_OK) . " consts exported:\n";
#foreach(@EXPORT_OK) { print STDERR "$_\n"; }
#my $val = main::thing("xyz");
#print STDERR "caller gave me $val\n";
#foreach my $arg (@ARGV) { print STDERR "arg $arg\n"; }
Author: swannman
Source Code: https://github.com/swannman/pdf2gerb
License: GPL-3.0 license
1618667723
how to create a Sidebar Menu using HTML and CSS only. Previously I have shared a Responsive Navigation Menu Bar using HTML & CSS only, now it’s time to create a Side Navigation Menu Bar that slides from the left or right side.
#sidebar menu using html css #side navigation menu html css #css side navigation menu bar #,pure css sidebar menu #side menu bar html css #side menu bar using html css
1649473200
!important
in CSS is a special notation that we can apply to a CSS declaration to override other conflicting rules for the matching selector.
When we work on web projects, it is natural that we have some style declarations that other styles overrule.
This is not an issue for an experienced developer who understands the core mechanism of CSS. However, it can be difficult for beginners to understand why the style declarations they expect are not applied by the browser.
So, instead of them focusing on resolving the issue naturally, they tend to go for the quick fix by adding the !important
declaration to enforce the style they expect. While this approach might work for that moment, it can also initiate another complex problem.
In this guide, we will review the following, including how to use !important
and when we should use it:
!important
declaration before we use it:is()
and other related pseudo-class functions!important
declaration?Enough said, let’s dive in.
Understanding the core principles of CSS will naturally enable us to know when it’s obvious to use the !important
declaration. In this section, we will walk through some of these mechanisms.
Consider the HTML and CSS code below, what color do you think the heading text will be?
First, the HTML:
<h2 class="mytitle">This is heading text</h2>
Then, the CSS:
h2 {
color: blue;
}
h2 {
color: green;
}
The text will render green! This is basic CSS fundamental. With the CSS cascade algorithm, the ordering of CSS rules matters. In this case, the declaration that comes last in the source code wins.
Normally, this is logical. In the first place, we should not repeat the same selector as we did above. CSS does not want repetition, so it uses the last declaration rule.
However, there are cases whereby we create generic styles for the root elements, like the h2
, and then add classes to style specific elements. Let’s consider the following example as well, starting with the HTML:
<h2>This is heading text</h2>
<h2 class="mytitle">This is heading text</h2>
Then, let’s see the CSS:
.mytitle {
color: blue;
}
h2 {
color: green;
}
In the above code, the first h2
element has no class applied, so it is obvious that it gets the green color of the h2
selector.
However, the second h2
element uses the rule for the class selector, .mytitle
, even when the element selector rule comes last in the CSS code. The reason for that is that the class selector has a higher specificity when compared to the element selector.
In other words, the weight applied to the declaration in a class selector is more than element selector’s weight.
Similarly, the declaration in an ID selector is more than that of the class selector. In this case, the red color in the code below takes precedence:
<h2 id="maintitle" class="mytitle">This is heading text</h2>
Followed by the CSS:
.mytitle {
color: blue;
}
#maintitle {
color: red;
}
h2 {
color: green;
}
Furthermore, an inline style
attribute takes precedence over the ID selector, starting with the HTML:
<h2 id="maintitle" style="color: black;" class="mytitle">This is heading text</h2>
Then followed by the CSS:
.mytitle {/*...*/}
#maintitle {/*...*/}
h2 {/*...*/}
This is the ideal priority flow in CSS and must be maintained to avoid anomalies. The !important
declaration most of the time comes when we are oblivious of these basic rules.
The inline style attribute and each of the selectors have values that browsers assign to them. That way, it knows which one has higher or lower priority. Think of this value as a number of four single digits with the style
attribute assigned the strongest weight value of 1000
.
This follows the ID with a value of 0100
, then class with 0010
, and finally the element selector with 0001
.
Sometimes we can combine selectors targeting specific elements, as seen in the example below:
<h2 id="maintitle" class="mytitle">This is heading text</h2>
Followed by the CSS:
h2.mytitle {
color: blue;
}
#maintitle {
color: red;
}
h2 {
color: green;
}
The specificity of the h2.mytitle
selector in the CSS above is the addition of h2
and .mytitle
. That is, 0001 + 0010 = 0011
. This total value, however, is less than that of the #maintitle
ID that is 0100
.
So, the browser uses the declaration in the ID selector to override other conflicting rules. In a case of equal weight, the last rule declaration wins.
Now that we know which rules are most relevant and why the browser applies them, it will become naturally obvious whether or not to use this !important
declaration.
!important
declaration before we use itBefore we consider using the !important
notation, we must ensure that we follow the specificity rule and use the CSS cascade.
In the code below, we have the h2
and h3
elements styled to be a red
color:
<h2 class="mytitle">This is heading II text</h2>
<h3 class="mytitle">This is heading III text</h3>
Then, .mytitle
in CSS:
.mytitle {
color: red;
}
But, let’s say at some point, we want to give the h3
element a blue
color. Adding a style rule like the one below would not change the color because the class has more weight and it’s more specific than the element selector, as we’ve learned:
.mytitle {...}
h3 {
color: blue;
}
However, using the !important
on the lesser weight makes the browser enforce that declaration over other conflicting rules:
.mytitle {...}
h3 {
color: blue !important;
}
This is because the !important
notation increases the weight of the declaration in the cascade order of precedence. What this means is that we’ve disrupted the normal priority flow. Hence, bad practice, and can lead to difficulties in code maintenance and debugging.
If at some other point, we want to override the above important rule, we can apply another !important
notation on a declaration with higher specificity (or the same if it is lower down in the source). It can then lead to something like this:
h3 {
color: blue !important;
}
/* several lines of rules */
.mytitle {
color: green !important;
}
This is bad and should be avoided. Instead, we should check if:
Well, let’s find out. Back to our style rules, we can enforce a blue
color on the h3
element by increasing the specificity score.
As seen below, we can combine selectors until their specificity score supersedes the conflicting rule. The h3.mytitle
selector gives a specificity score of 0011
, which is more than the .mytitle
of 0010
score:
.mytitle {...}
h3.mytitle {
color: blue;
}
As we can see, instead of using the !important
declaration to enforce a rule, we focus on increasing the specificity score.
:is()
and other related pseudo-class functionsSometimes, we may trace issues to a pseudo-class function. So, knowing how it works can save us a lot of stress. Let’s see another example.
Imagine we are working on a project and see the following code:
<h1 id="header">
heading <span>span it</span>
<a href="#">link it</a>
</h1>
<p class="paragraph">
paragraph <span>span it</span>
<a href="">link it</a>
</p>
Using the following CSS rules gives us the output after:
:is(#header, p) span,
:is(#header, p) a {
color: red;
}
Now, let’s say we want to give the span
and the link text in the paragraph another color of blue
. We can do this by adding the following rule:
.paragraph span,
.paragraph a {
color: blue;
}
The earlier rule will override the blue
color despite being further down the line:
As a quick fix, we can enforce our blue
color by using the !important
notation like so:
:is(#header, p) span,
:is(#header, p) a {...}
.paragraph span,
.paragraph a {
color: blue !important;
}
But, as you may guess, that is bad practice, so we must not be quick to use the !important
notation. Instead, we can start by analyzing how every selector works. The :is()
is used in the code is a pseudo-class function for writing mega selectors in a more compressed form.
So, here is the following rule in the above code:
:is(#header, p) span,
:is(#header, p) a {
color: red;
}
Which is equivalent to the following:
#header span,
p span,
#header a,
p a {
color: red;
}
So, why is .paragraph span
and .paragraph a
not overriding the color despite having a specificity score of 0011
, which is higher than 0002
of the p span
and p a
.
Well, every selector in the :is()
uses the highest specificity in the list of arguments. In that case, both the #header
and the p
in the :is(#header, p)
uses the specificity score of the #header
, which is 0100
. Thus, the browser sticks to its value because it has a higher specificity.
Thus, anytime we see this type of conflict, we are better off not using the pseudo-class function and sticking to its equivalent like the following:
#header span,
p span,
#header a,
p a {
color: red;
}
Now, we should be able to see the expected result without using the !important
notation that disrupts cascade order.
You can see for yourself on CodeSandbox.
!important
declaration?Below are a few occasions where using the !important
notation is recommended.
Assuming we want to style all buttons on a page to look the same, we can write a CSS rule that can be reused across a page. Let’s take a look at the following markup and style below:
<p>Subscribe button : <a class="btn" href="#">Subscribe</a></p>
<section class="content">
<p>
This <a href="#" class="btn">button</a> style is affected by a higher
specificity value .
</p>
A link here: <a href="#">Dont click</a>
</section>
Followed by the CSS:
.btn {
display: inline-block;
background: #99f2f5;
padding: 8px 10px;
border: 1px solid #99f2f5;
border-radius: 4px;
color: black;
font-weight: normal;
text-decoration: none;
}
.content a {
color: blue;
font-weight: bold;
text-decoration: underline;
}
In the above code, we can see that the button link within the section
element is targeted by both selectors in the CSS. And, we learned that for conflicting rules, the browser will use the most specific rule. As we expect, .content a
has a score of 0011
while .btn
has a score of 0010
.
The page will look like this:
In this case, we can enforce the .btn
rule by adding the !important
notation to the conflicting declarations like this:
.btn {
/* ... */
color: black !important;
font-weight: normal !important;
text-decoration: none !important;
}
The page now looks as we expect:
See for yourself on CodeSandbox.
This mostly happens when we don’t have total control over the working code. Sometimes, when we work with a content management system like WordPress, we may find that an inline CSS style in our WordPress theme is overruling our custom style.
In this case, the !important
declaration is handy to override the theme inline style.
The !important
declaration is never meant to be used as we desire. We must only use it if absolutely necessary, such as a situation where we have less control over the code or very extreme cases in our own code.
Whether or not we use it depends on how we understand the core CSS mechanism, and in this tutorial, we covered that as well.
I hope you enjoyed reading this post. If you have questions or contributions, share your thought in the comment section and remember to share this tutorial around the web.
Source: https://blog.logrocket.com/understanding-css-important-declaration/
1619713680
#css #html #pure css card #html and css #design
1649426848
!important
en CSS es una notación especial que podemos aplicar a una declaración de CSS para anular otras reglas en conflicto para el selector coincidente.
Cuando trabajamos en proyectos web, es natural que tengamos algunas declaraciones de estilo que anulan otros estilos.
Este no es un problema para un desarrollador experimentado que comprende el mecanismo central de CSS. Sin embargo, puede ser difícil para los principiantes entender por qué el navegador no aplica las declaraciones de estilo que esperan.
Entonces, en lugar de enfocarse en resolver el problema de forma natural, tienden a buscar la solución rápida agregando la !important
declaración para hacer cumplir el estilo que esperan. Si bien este enfoque podría funcionar en ese momento, también puede iniciar otro problema complejo.
En esta guía, revisaremos lo siguiente, incluido cómo usarlo !important
y cuándo debemos usarlo:
!important
declaración antes de usarla:is()
y otras funciones de pseudoclase relacionadas!important
declaración?Suficiente dicho, vamos a sumergirnos.
Comprender los principios básicos de CSS naturalmente nos permitirá saber cuándo es obvio usar la !important
declaración. En esta sección, analizaremos algunos de estos mecanismos.
Considere el código HTML y CSS a continuación, ¿de qué color cree que será el texto del encabezado?
Primero, el HTML:
<h2 class="mytitle">This is heading text</h2>
Entonces, el CSS:
h2 {
color: blue;
}
h2 {
color: green;
}
¡El texto se volverá verde! Esto es CSS básico fundamental. Con el algoritmo de cascada de CSS , el orden de las reglas de CSS importa. En este caso, gana la última declaración en el código fuente.
Normalmente, esto es lógico. En primer lugar, no debemos repetir el mismo selector que hicimos anteriormente. CSS no quiere repetición, por lo que usa la última regla de declaración.
Sin embargo, hay casos en los que creamos estilos genéricos para los elementos raíz, como el h2
, y luego agregamos clases para diseñar elementos específicos. Consideremos también el siguiente ejemplo, comenzando con el HTML:
<h2>This is heading text</h2>
<h2 class="mytitle">This is heading text</h2>
Entonces, veamos el CSS:
.mytitle {
color: blue;
}
h2 {
color: green;
}
En el código anterior, el primer h2
elemento no tiene clase aplicada, por lo que es obvio que obtiene el color verde del h2
selector.
Sin embargo, el segundo h2
elemento usa la regla para el selector de clase .mytitle
, incluso cuando la regla del selector de elementos viene en último lugar en el código CSS. La razón de esto es que el selector de clase tiene una mayor especificidad en comparación con el selector de elementos.
En otras palabras, el peso aplicado a la declaración en un selector de clase es mayor que el peso del selector de elementos.
De manera similar, la declaración en un selector de ID es más que la del selector de clase. En este caso, el color rojo en el siguiente código tiene prioridad:
<h2 id="maintitle" class="mytitle">This is heading text</h2>
Seguido por el CSS:
.mytitle {
color: blue;
}
#maintitle {
color: red;
}
h2 {
color: green;
}
Además, un style
atributo en línea tiene prioridad sobre el selector de ID, comenzando con el HTML:
<h2 id="maintitle" style="color: black;" class="mytitle">This is heading text</h2>
Luego seguido por el CSS:
.mytitle {/*...*/}
#maintitle {/*...*/}
h2 {/*...*/}
Este es el flujo de prioridad ideal en CSS y debe mantenerse para evitar anomalías. La !important
declaración la mayoría de las veces llega cuando nos olvidamos de estas reglas básicas.
El atributo de estilo en línea y cada uno de los selectores tienen valores que les asignan los navegadores. De esa manera, sabe cuál tiene mayor o menor prioridad. Piense en este valor como un número de cuatro dígitos individuales con el style
atributo asignado al valor de ponderación más fuerte de 1000
.
Esto sigue al ID con un valor de 0100
, luego a la clase con 0010
, y finalmente al selector de elementos con 0001
.
A veces podemos combinar selectores dirigidos a elementos específicos, como se ve en el siguiente ejemplo:
<h2 id="maintitle" class="mytitle">This is heading text</h2>
Seguido por el CSS:
h2.mytitle {
color: blue;
}
#maintitle {
color: red;
}
h2 {
color: green;
}
La especificidad del h2.mytitle
selector en el CSS anterior es la adición de h2
y .mytitle
. Es decir, 0001 + 0010 = 0011
. Este valor total, sin embargo, es menor que el del #maintitle
ID que es 0100
.
Entonces, el navegador usa la declaración en el selector de ID para anular otras reglas en conflicto. En un caso de igual peso, gana la declaración de la última regla.
Ahora que sabemos qué reglas son las más relevantes y por qué el navegador las aplica, será obvio si usar o no esta !important
declaración.
!important
declaración antes de usarlaAntes de considerar el uso de la !important
notación, debemos asegurarnos de que seguimos la regla de especificidad y usamos la cascada CSS.
En el siguiente código, tenemos los elementos h2
y h3
diseñados para ser un red
color:
<h2 class="mytitle">This is heading II text</h2>
<h3 class="mytitle">This is heading III text</h3>
Luego, .mytitle
en CSS:
.mytitle {
color: red;
}
Pero digamos que en algún momento queremos darle un color al h3
elemento . blue
Agregar una regla de estilo como la siguiente no cambiaría el color porque la clase tiene más peso y es más específica que el selector de elementos, como hemos aprendido:
.mytitle {...}
h3 {
color: blue;
}
Sin embargo, usar !important
on the lesserweight hace que el navegador aplique esa declaración sobre otras reglas en conflicto:
.mytitle {...}
h3 {
color: blue !important;
}
Esto se debe a que la !important
notación aumenta el peso de la declaración en el orden de precedencia en cascada. Lo que esto significa es que hemos interrumpido el flujo de prioridad normal. Por lo tanto, es una mala práctica y puede generar dificultades en el mantenimiento y la depuración del código.
Si en algún otro punto, queremos anular la regla importante anterior, podemos aplicar otra !important
notación en una declaración con mayor especificidad (o lo mismo si está más abajo en la fuente). Entonces puede conducir a algo como esto:
h3 {
color: blue !important;
}
/* several lines of rules */
.mytitle {
color: green !important;
}
Esto es malo y debe evitarse. En su lugar, debemos comprobar si:
Bueno, averigüémoslo. Volviendo a nuestras reglas de estilo, podemos imponer un blue
color en el h3
elemento aumentando la puntuación de especificidad.
Como se ve a continuación, podemos combinar selectores hasta que su puntaje de especificidad reemplace la regla en conflicto. El h3.mytitle
selector otorga una puntuación de especificidad de 0011
, que es mayor que la puntuación .mytitle
de :0010
.mytitle {...}
h3.mytitle {
color: blue;
}
Como podemos ver, en lugar de usar la !important
declaración para hacer cumplir una regla, nos enfocamos en aumentar el puntaje de especificidad.
:is()
y otras funciones de pseudoclase relacionadasA veces, podemos rastrear problemas hasta una función de pseudoclase. Entonces, saber cómo funciona puede ahorrarnos mucho estrés. Veamos otro ejemplo.
Imagina que estamos trabajando en un proyecto y vemos el siguiente código:
<h1 id="header">
heading <span>span it</span>
<a href="#">link it</a>
</h1>
<p class="paragraph">
paragraph <span>span it</span>
<a href="">link it</a>
</p>
El uso de las siguientes reglas CSS nos da el resultado después:
:is(#header, p) span,
:is(#header, p) a {
color: red;
}
Ahora, digamos que queremos darle al span
y al texto del enlace en el párrafo otro color de blue
. Podemos hacer esto agregando la siguiente regla:
.paragraph span,
.paragraph a {
color: blue;
}
La regla anterior anulará el blue
color a pesar de estar más abajo en la línea:
Como una solución rápida, podemos hacer cumplir nuestro blue
color usando la !important
notación de esta manera:
:is(#header, p) span,
:is(#header, p) a {...}
.paragraph span,
.paragraph a {
color: blue !important;
}
Pero, como puede suponer, esa es una mala práctica, por lo que no debemos apresurarnos a usar la !important
notación. En cambio, podemos comenzar analizando cómo funciona cada selector. La :is()
que se usa en el código es una función de pseudoclase para escribir megaselectores en una forma más comprimida.
Entonces, aquí está la siguiente regla en el código anterior:
:is(#header, p) span,
:is(#header, p) a {
color: red;
}
Lo cual es equivalente a lo siguiente:
#header span,
p span,
#header a,
p a {
color: red;
}
Entonces, ¿por qué .paragraph span
y .paragraph a
no anula el color a pesar de tener un puntaje de especificidad de 0011
, que es más alto que 0002
el de p span
y p a
.
Bueno, cada selector en :is()
usa la especificidad más alta en la lista de argumentos. En ese caso, tanto the #header
como the p
in the :is(#header, p)
usan la puntuación de especificidad de #header
, que es 0100
. Por lo tanto, el navegador mantiene su valor porque tiene una mayor especificidad.
Por lo tanto, cada vez que vemos este tipo de conflicto, es mejor no usar la función de pseudoclase y apegarnos a su equivalente como el siguiente:
#header span,
p span,
#header a,
p a {
color: red;
}
Ahora, deberíamos poder ver el resultado esperado sin usar la !important
notación que interrumpe el orden en cascada.
Puedes verlo por ti mismo en CodeSandbox .
!important
declaración?A continuación se presentan algunas ocasiones en las !important
que se recomienda usar la notación.
Suponiendo que queremos diseñar todos los botones de una página para que tengan el mismo aspecto, podemos escribir una regla CSS que se puede reutilizar en una página. Echemos un vistazo al siguiente marcado y estilo a continuación:
<p>Subscribe button : <a class="btn" href="#">Subscribe</a></p>
<section class="content">
<p>
This <a href="#" class="btn">button</a> style is affected by a higher
specificity value .
</p>
A link here: <a href="#">Dont click</a>
</section>
Seguido por el CSS:
.btn {
display: inline-block;
background: #99f2f5;
padding: 8px 10px;
border: 1px solid #99f2f5;
border-radius: 4px;
color: black;
font-weight: normal;
text-decoration: none;
}
.content a {
color: blue;
font-weight: bold;
text-decoration: underline;
}
En el código anterior, podemos ver que el enlace del botón dentro del section
elemento está dirigido por ambos selectores en el CSS. Y aprendimos que para las reglas en conflicto, el navegador usará la regla más específica. Como esperábamos, .content a
tiene una puntuación de 0011
while .btn
tiene una puntuación de 0010
.
La página se verá así:
En este caso, podemos hacer cumplir la .btn
regla agregando la !important
notación a las declaraciones en conflicto como esta:
.btn {
/* ... */
color: black !important;
font-weight: normal !important;
text-decoration: none !important;
}
La página ahora se ve como esperamos:
Compruébelo usted mismo en CodeSandbox .
Esto sucede principalmente cuando no tenemos control total sobre el código de trabajo. A veces, cuando trabajamos con un sistema de administración de contenido como WordPress, podemos encontrar que un estilo CSS en línea en nuestro tema de WordPress anula nuestro estilo personalizado.
En este caso, la !important
declaración es útil para anular el estilo en línea del tema.
La !important
declaración nunca está destinada a ser utilizada como deseamos. Solo debemos usarlo si es absolutamente necesario, como una situación en la que tenemos menos control sobre el código o casos muy extremos en nuestro propio código.
Si lo usamos o no depende de cómo entendamos el mecanismo central de CSS, y en este tutorial también cubrimos eso.
Espero que hayas disfrutado leyendo esta publicación. Si tiene preguntas o contribuciones, comparta su opinión en la sección de comentarios y recuerde compartir este tutorial en la web.
Fuente: https://blog.logrocket.com/understanding-css-important-declaration/