Francesca Francesca - 6 months ago 26
CSS Question

Full width of singular item within a flex container

I'm working on a responsive design, I really don't want to change the HTML markup but rather make what I have work.

I have a container with three elements (a category, an image thumbnail and a div containing text).

HTML



<article class="featured">
<div class="category">
<a href="/#/#/">Category name</a>
</div>
<a href="/my-img/" class="thumb-wrapper">
<div class="thumb" style="background-image: url(http://my-image-path);"></div>
</a>
<div class="text">
<h2><a href="/#/">Lorem ipsum</a></h2>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed sit amet vehicula erat, eget volutpat erat. In imperdiet ligula id mauris convallis aliquet quis congue dui. Integer vulputate erat augue, ac aliquam velit iaculis at. </p>
</div>
</article>


So there are three child elements of
article
:
div.category
,
a
and
div.text


I want to make
div.category
sit full width/
max-width:100%
across
article
and I then want
a
and
div.text
to sit next to each other using flex. I've already got this working elsewhere, but not when
div.category
is present.

Here's a little mock-up

enter image description here

As I said, I don't want to change the HTML structure and I would like to make use of
flex
as this is what I have used elsewhere.

My problem is making
div.category
full width when its parent (
article
) has
display:flex;
applied. Essentially I am trying to overwrite the effect of
flex
on just
div.category


JS Fiddle

I have tried applying
width:100%
to the category, and then also applying
flex-shrink:0;
so that it cannot be shrunk, but then the second two elements don't wrap onto the next line. And using
flex-wrap
to make them wrap doesn't have them sitting in one row.

Answer

You can use flex: 0 0 50% on .thumb-wrapper and .text , and flex: 0 0 100% on .category, and don't forget to set flex-wrap: wrap on article

body, html {
  margin: 0;
  padding: 0;
}
* {
  box-sizing: border-box;
}
article {
  display: flex;
  flex-wrap: wrap;
}
.category, .thumb-wrapper, .text {
  border: 1px solid black;
  flex: 0 0 50%;
  padding: 10px;
}
.category {
  flex: 0 0 100%;
}
.thumb-wrapper, .thumb {
  display: flex;
  flex: 1;
  background-position: center;
}
<article class="featured">
  <div class="category">
    <a href="/#/#/">Category name</a>
  </div>
  <a href="/my-img/" class="thumb-wrapper">
    <div class="thumb" style="background-image: url('http://placehold.it/350x150');"></div>
  </a>
  <div class="text">
    <h2><a href="/#/">Lorem ipsum</a></h2>
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed sit amet vehicula erat, eget volutpat erat. In imperdiet ligula id mauris convallis aliquet quis congue dui. Integer vulputate erat augue, ac aliquam velit iaculis at.</p>
  </div>
</article>

Comments