B Markson B Markson - 3 months ago 15
CSS Question

Line segment won't stay under h2 tag

So, I've just started learning HTML/CSS and I've been trying to figure out how to 'stick' a line under an h2 tag. What I mean by this is that in the HTML there is an h2 tag called Instructions followed by a div tag that contains 3 other divs that make up a line segment. By default the line is on the left side (naturally), but what I want to do is have the line stuck under the h2 tag so when the browser is extended or shrunk the line stays directly under the h2 tag instead of moving across the screen by itself.

I came across this site: http://www.barelyfitz.com/screencast/html-training/css/positioning/ and I was using it to try and see if absolute/relative positioning would help here. I guess I'm doing it horribly wrong since it doesn't seem to help.

I'm providing HTML/CSS and a jsfiddle below (The jsfiddle doesn't show how the line moves around when the browser is extended/shrunk, though so I'm hoping you get what I mean). If you can help guide me or give me some resources to understand what I need to do better that would be great :D

I'm sure this is trivial, but I'm trying to do my due diligence in learning it. There were a lot of different methods (I think) I found, but they seemed kinda complex.

HTML

<div id="instructions_box">
<h2>Instructions</h2>
<div class="line_divider">
<div class="blue_line"></div>
<div class="yellow_line"></div>
<div class="blue_line"></div>
</div>
</div>


CSS

#instructions_box{
display: inline-block;
//position: relative;
}

.line_divider{
background-color: aqua;
//position: absolute;
//bottom: 0;
//right: 2rem;
}

.blue_line{
height: 2px;
width: 50px;
background-color: rgb(0,0,139);
float: left;
}

.yellow_line{
height: 2px;
width: 90px;
background-color: yellow;
float: left;
}

#instructions_box h2{
text-align: center;
}


https://jsfiddle.net/10szzwvs/1/

Thanks

Answer

The wrapping you're seeing is, I think, due to the fixed widths you're using. Change your line width to percentages and it wont wrap on any size screen. Note you'll need to add your visual spacing elsewhere, e.g. on the h2 itself.

#instructions_box{
   display: inline-block;
}
#instructions_box h2{
   text-align: center;
   padding: 0 25px 0;    /* visual spacing */
   margin: 0;
}

.line_divider{
   background-color: aqua;
}

.blue_line{
   height: 2px;
   width: 30%;    /* dynamic width here */
   background-color: rgb(0,0,139);
   float: left;  
}

.yellow_line{
   height: 2px;
   width: 40%;    /* dynamic width here */
   background-color: yellow;
   float: left;  
}
<div id="instructions_box">
  <h2>Instructions</h2>
  <div class="line_divider">
    <div class="blue_line"></div>
    <div class="yellow_line"></div>
    <div class="blue_line"></div>
  </div>
</div>