Siendo específico

9/Ene/2008 33791

Este tema debe ser uno de los artículos griales de CSSLab, y podría aportar en la solución de más de algún problema con el maqueteado CSS. La especificidad es una técnica que debe ser entendida muy a fondo, para que pueda ser abordada sin problemas posteriores, donde lo más común es cuando se escriben estilos para un mismo elemento y el browser no lo despliega como lo estipulamos. En esos momentos, lo más probable (aparte del error de que pueda estar mal escrito) es que haya conflictos de especificidad. Y mientras más grandes los archivos CSS (grandes me refiero a más de 1000 líneas), más difícil es controlar estos conflictos.

Son varias las reglas que implican la especificidad. Comencemos.

1.

Si los selectores son iguales, entonces el último escrito (el de más abajo en el código, ya que el browser lee los archivos de arriba hacia abajo) es el que toma importancia:


p { font-size: 1em; }
p { font-size: 1.5em; }

Entonces <p> tendrá el tamaño de texto de 1.5em. Esto es cuando los selectores son declarados de la misma forma, como en el ejemplo anterior. Vamos con otro:

2.

Para: <ul><li><a href="">Link</a></li></ul>


ul li a { color: #f00 }
a { color: #333 }

Si siguiéramos la misma filosofía, el link de una lista tendría color gris oscuro porque fue declarado después. Pero como hemos sido más específico diciendo que el link en un elemento de una lista (ul li a) es rojo, éste gana predominancia y finalmente se muestra rojo, no gris porque hemos sido más específicos con ello. Básicamente, esta regla dice: mientras más específico el selector, más preferencia tendrá por sobre otros estilos. Existen cálculos creados para ayudar a evitar errores en esto:

Selectores HTML tienen valor 1

p tendrá especificidad 1

(p = 1)

ul li a tendrá especificidad 3

(ul+li+a = 1+1+1 =  3)

Selectores de Class tienen valor 10

.nombreclass tendrá especificidad 10

(.nombreclass = 10)

div p.nombreclass tendrá especificidad 12

(div+p+.nombreclass = 1+1+10)

Selectores de ID tienen valor 100

#nombreid tendrá especificidad 100

(#nombreid = 100)

body #nombreid .nombreclass p tendrá especificidad 112

body+#nombreid+.nombreclass+p = 1+100+10+1 = 112

3.

Selectores universales tienen especificidad 0, tales como * y body

4.

Estilos inline (esos que son dados dentro del mismo HTML mediante el atributo style="") tienen la mayor especificidad de todas.

<p style="color: blue;">Texto en azul</p>

Finalmente, un par de consejos:

  • Trata de evitar !important. De eso se trata todo esto, entender cómo funciona para que no tengas que parchar utilizando métodos que causan más problemas de los que soluciona.
  • – No te vuelvas loco especificando. Sería insano toparse con:
body div#container div#menu ul li ul.submenu li a
  • – Ahorra especificidad no yendo atrás más que 2 o 3 niveles para evitar conflictos, como por ejemplo:
#menu li a

Links:

Comentarios

  1. personal injury lawyers sydney [#]

    QLD conveyancing fees can differ widely.

    Stop by my web-site: personal injury lawyers sydney

  2. japanese god of war hachiman [#]

    Ebisu came from as a patron japanese god of war hachiman of anglers in Japan.

  3. Laurinda [#]

    Don’t lose time constructing the incorrect functions.

    Have a look at my blog post; product roadmap software free (Laurinda)

  4. Ahmad [#]

    I must thank you for the efforts you’ve put in writing this
    blog. I really hope to check out the same high-grade content from you later on as well.
    In fact, your creative writing abilities has encouraged me to get my own,
    personal site now 😉

    Feel free to visit my web site buy full spectrum cbd uk; Ahmad,

  5. how to style a hoodie men [#]

    Dimensions are given in both centermeters
    and also inches.

    Here is my page: how to style a hoodie men

  6. electrician local to me [#]

    I was recommended this web site by means of my cousin. I’m not sure whether this put up is written by means of him as no one else recognize such targeted
    about my trouble. You’re incredible! Thanks!

    Also visit my page :: electrician local to me

  7. pharmacy online [#]

    Hey! This is my first visit to your blog! We are a team of volunteers and starting a
    new project in a community in the same niche.
    Your blog provided us beneficial information to work
    on. You have done a marvellous job!

  8. bishamonten the japanese god of war [#]

    bishamonten the japanese god of war became a
    patron of competitors in Japan.

  9. lawyer salaries sydney [#]

    QLD conveyancing charges can differ commonly.

    Have a look at my website :: lawyer salaries sydney

  10. krg conveyancing brisbane reviews [#]

    We’re conveyancers, powered by legal representatives.

    Feel free to visit my site: krg conveyancing brisbane reviews

  11. item391057893 [#]

    QLD conveyancing fees can vary extensively.

    my web blog item391057893

  12. Brenna [#]

    Nice blog here! Also your website loads up fast!
    What web host are you using? Can I get your affiliate link to your host?
    I wish my web site loaded up as quickly as yours lol

    My blog; Brenna

  13. https://thelaware.com [#]

    This is really attention-grabbing, You’re an overly professional blogger.
    I have joined your feed and look ahead to in search of extra of your
    great post. Also, I have shared your website in my social networks

    Here is my blog: https://thelaware.com

  14. where to buy broad spectrum cbd [#]

    Wow that was strange. I just wrote an incredibly long comment but after I clicked submit my comment
    didn’t appear. Grrrr… well I’m not writing all that over again. Regardless,
    just wanted where to buy broad spectrum cbd say excellent blog!

  15. bulk broad spectrum hemp oil [#]

    I like what you guys are up too. This sort of clever
    work and reporting! Keep up the awesome works guys I’ve added
    you guys to blogroll.

    Also visit my website … bulk broad spectrum hemp oil

  16. project management timeline software free [#]

    Do not waste time building the incorrect functions.

    Also visit my homepage … project management timeline software free

  17. Bookmarks [#]

    Let your individuals build your following features.

    My webpage: Bookmarks

  18. home electrician near me [#]

    Aw, this was a really nice post. Finding the time and actual effort to generate a superb article… but what can I say…
    I put things off a lot and don’t seem to get nearly anything done.

    Also visit my blog post :: home electrician near me

  19. best product roadmap tools [#]

    Allow your customers construct your following
    functions.

    My page … best product roadmap tools

  20. Bookmarks [#]

    Accumulate consumer responses and also feature suggestions.

    my web site Bookmarks

  21. email marketing database [#]

    Hello, I enjoy reading all of your post. I like to write a little comment to suppkrt you.

  22. i need an electrician [#]

    Hi to every single one, it’s actually a pleasant for me to pay
    a quick visit this website, it consists of valuable Information.

    Here is my blog post … i need an electrician

  23. Local Electricians [#]

    I truly love your website.. Great colors & theme.
    Did you build this website yourself? Please reply back
    as I’m looking to create my very own blog and
    would love to know where you got this from or just what the theme is
    called. Cheers!

    Feel free to visit my homepage: Local Electricians

  24. i thought about this [#]

    Definitely, what a splendid site and educative posts, I surely will bookmark your site.Have
    an awsome day!

  25. play blackjack online [#]

    Appreciate this post. Let me try it out.

  26. голые девки ставрополья [#]

    голые девки ставрополья фото жен и мужей голых

  27. electrician near me 24/7 [#]

    Hey, I think your website might be having browser compatibility issues.
    When I look at your blog site in Ie, it looks fine but when opening in Internet
    Explorer, it has some overlapping. I just wanted to give you a quick heads up!
    Other then that, amazing blog!

    Here is my homepage; electrician near me 24/7

  28. mobile electrician [#]

    There’s definately a lot to find out about this subject.

    I love all of the points you have made.

    my web-site: mobile electrician

  29. Adultfrienedfinder app [#]

    Have you ever considered creating an e-book or guest authoring
    on other blogs? I have a blog based on the same subjects you discuss and would really like to have you share some stories/information. I know my audience would appreciate your work.
    If you’re even remotely interested, feel free to shoot me
    an e-mail.

  30. private adhd assessment bristol [#]

    Excellent article. I will be facing some of these
    issues as well..

    my webpage … private adhd assessment bristol

  31. local electrician near me [#]

    Hi my family member! I want to say that this post is amazing,
    great written and come with approximately all
    vital infos. I’d like to look extra posts like this .

    Also visit my webpage – local electrician near me

  32. puffco peak Smart rig [#]

    Someone essentially lend a hand to make seriously articles I would state.
    This is the first time I frequented your website
    page and so far? I surprised with the research you made to make this actual put up amazing.
    Wonderful activity!

    Also visit my homepage … puffco peak Smart rig

  33. puffco [#]

    I’m really impressed along with your writing abilities and
    also with the layout to your blog. Is that this a paid topic or did you customize it yourself?
    Anyway stay up the excellent high quality writing, it is rare to look a great blog like this one these days..

    My blog post puffco

  34. Puffco Peak [#]

    Why viewers still make use of to read news papers when in this
    technological globe the whole thing is existing on net?

    Also visit my site Puffco Peak

  35. nnetw.org [#]

    This is really interesting, You’re a very skilled
    blogger. I have joined your rss feed and look forward to seeking more
    of your wonderful post. Also, I have shared your website in my
    social networks!

  36. electrician [#]

    My family members all the time say that I am killing my time here at
    net, however I know I am getting knowledge all the time by reading
    such nice articles.

    Take a look at my blog: electrician

  37. private psychiatrist adhd [#]

    Ahaa, its fastidious discussion on the topic of this paragraph here at
    this blog, I have read all that, so now me also commenting at this place.

    Stop by my web-site – private psychiatrist adhd

  38. industrial electrician near me [#]

    always i used to read smaller articles or reviews that also clear their motive, and that is also happening with this post which I
    am reading here.

    Here is my web blog … industrial electrician near me

  39. electrician [#]

    My family members all the time say that I am killing my time here at
    net, however I know I am getting knowledge all the time by reading
    such nice articles.

    Take a look at my blog: electrician

  40. 24 hr electrician [#]

    Hi there to all, how is all, I think every one is getting more
    from this site, and your views are nice in support of new users.

    Visit my homepage – 24 hr electrician

  41. fun555 ทางเข้าล่าสุด [#]

    My brother suggested I might like this website.

    He was totally right. This post actually made my day.
    You cann’t imagine just how much time I had spent for this information! Thanks!

CSSLab