:before psuedo element not working on h1 tag

痞子三分冷 提交于 2019-12-25 19:05:27

问题


I cannot get the :before pseudo class to insert an icon font before a div containing H1 tags. All the examples I see online use a p or i to insert, however I want to use H1 tags because each tag will have a separate ID and class that correspond to some animate.css fade and delay effect.

For simplicity sake I have replaced the font icon with a hash symbol in the example below. The idea is the icon-font will appear before the div, not each h1 tag (this I can do) - in other words; four lines of text and one icon font. My feeling is this something to do with the display property or nested/ child, but at a complete loss how to fix. Any help much appreciated.

<!DOCTYPE html>
<html>
<head>
<style type="text/css">

    #wrapper {
    max-width: 800px;
    margin:0 auto;
    background-color: rgb(201, 238, 219);
    }

    .theLines {
    width: 300px;
    border: solid 1px black;
    padding: 20px;
    }


    .theLines:before{
    font-family: ;
    content: "#";
    color:red;
    font-size:3em;
    border: solid 1px red;
    }

</style>
</head>


<body id="wrapper" class="">

        <div id="container">
            <div class="theLines">
                <h1>Line 1</h1>
                <h1>Line 2</h1>
                <h1>Line 3</h1>
                <h1>Line 4</h1>
            </div>
        </div>

</body>
</html>

回答1:


One solution is to use positioning relative to #container to achieve this:

Demo Fiddle

<div id="container">
    <div class="theLines">
         <h1>Line 1</h1>
         <h1>Line 2</h1>
         <h1>Line 3</h1>
         <h1>Line 4</h1>
    </div>
</div>

CSS

 #wrapper {
     max-width: 800px;
     margin:0 auto;
     background-color: rgb(201, 238, 219);
 }
 #container {
     position:relative; /* <-- set 'base' positioning */
 }
 .theLines {
     width: 300px;
     border: solid 1px black;
     padding: 20px; 
     margin-left:40px; /* <-- move away from left side of #container */
 }
 .theLines:before {
     content:"#";
     color:red;
     font-size:3em;
     border: solid 1px red;
     position:absolute; /* allow for adjacent positioning relative to other children of #container */
     left:0; /* position on left hand side of #container */
     display:inline-block;
 }


来源:https://stackoverflow.com/questions/27144141/before-psuedo-element-not-working-on-h1-tag

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!