Evanss
Evanss

Reputation: 23583

Wrap floated text at smaller screen widths?

Im floating a heading to the left and a div containing a few links to the right. At wide screen widths everything is fine.

At smaller widths the links appear under the heading. Instead I need the heading to wrap.

My content is dynamic, the heading text will vary in length and the number of links with vary also. Therefore I dont believe I can use % widths.

I can alter the HTML however I need to keep the heading above the links in the HTML. This is because for the smallest media query the heading will be above the links.

enter image description here

http://codepen.io/anon/pen/OPxbxG

<div class="container">
  <h1>Title goes here</h1>
  <div class="links">
    <a href="#">Link one</a>
    <a href="#">Link two</a>
  </div>
</div>

.container {
  background: grey;
  width: 60%;
  margin: auto;
  overflow: auto;
}
h1 {
  float: left;
  margin: 0;
}
.links {
  float: right;
}

Upvotes: 1

Views: 3933

Answers (3)

Danield
Danield

Reputation: 125463

1) Place the links first in the markup

2) Set overflow:hidden (or auto) on the heading instead of float:left

Updated Codepen (Resize page to see this work)

The reason why this works is that setting overflow:hidden (or auto) establishes a new block formatting context. For more info see this post.

.container {
  background: grey;
  width: 60%;
  margin: auto;
  overflow: auto;
}
h1 {
  overflow: hidden;
  margin: 0;
}
.links {
  float: right;
}
<div class="container">
  <div class="links">
    <a href="#">Link one</a>
    <a href="#">Link two</a>
  </div>
  <h1>Title goes here</h1>

</div>

Upvotes: 1

Danield
Danield

Reputation: 125463

If CSS3 is an option, then you can use flexbox to acheive this, without having to change the order of the markup.

Just set display:flex on the container and flex:1 on the heading to fill remaining viewport width (not taken by the links)

Updated Codepen

.container {
  background: grey;
  width: 60%;
  margin: auto;
  overflow: auto;
  display: flex;
}
h1 {
  flex: 1;
  margin: 0;
}
.links {
  float: right;
}
<div class="container">
  <h1>Title goes here</h1>
  <div class="links">
    <a href="#">Link one</a>
    <a href="#">Link two</a>
  </div>
</div>

Upvotes: 0

tomtomtom
tomtomtom

Reputation: 899

Did you mean something like that : http://codepen.io/anon/pen/ZYXBoB ?

I just remove the float:left; on the title and put it after the menu in DOM.

Upvotes: 1

Related Questions