찾다
웹 프론트엔드HTML 튜토리얼如何使用Flexbox构建新闻站点布局_html/css_WEB-ITnose

英文原文: http://webdesign.tutsplus.com/tutorials/how-to-build-a-news-website-layout-with-flexbox--cms-26611

It’s not necessary to understand every aspect of Flexbox before you can jump in and get started. In this tutorial, we’re going to introduce a few features of Flexbox whilst designing a “news layout” like the one you can find on The Guardian .

The reason we’re using Flexbox is that it provides very powerful features:

  • we can easily make responsive columns
  • we can make columns of equal height
  • we can push content to the bottom of a container

So let’s get started!

1. Start with Two Columns

Creating columns in CSS has always been a challenge. For a long time, the only options were to use floats or tables, but they both had their own issues.

Flexbox makes the process easier, giving us:

  • cleaner code : we only need a container with display: flex
  • no need to clear floats, preventing unexpected layout behavior
  • semantic markup
  • flexibility : we can resize, stretch, align the columns in a few lines of CSS

Let’s start by making two columns; one that’s 2/3 of the width of our container, and one that’s 1/3.

<div class="columns"> <div class="column main-column"> 2/3 column </div> <div class="column"> 1/3 column </div></div>

There are two elements here:

  • the columns container
  • two column children, one with an additional class of main-column which we’ll use to make it wider

.columns { display: flex;}.column { flex: 1;}.main-column { flex: 2;}

As the main column has a flex value of 2, it will take up twice as much space as the other column.

By adding some additional visual styles, here’s what we get:

2. Make Each Column a Flexbox Container

Each of these two columns will contain several articles stacked vertically, so we’re going to turn the column elements into Flexbox containers too. We want:

  • the articles to be stacked vertically
  • the articles to stretch and fill the available space

.column { display: flex; flex-direction: column; /* Makes the articles stacked vertically */}.article { flex: 1; /* Stretches the articles to fill up the remaining space */}

The flex-direction: column rule on the container, combined with the flex: 1 rule on the children ensures that the articles will fill up the whole vertical space, keeping our first two columns the same height.

3. Make Each Article a Flexbox Container

Now, to give us extra control, let’s turn each article into a Flexbox container too. Each of them will contain:

  • a title
  • a paragraph
  • an information bar with the author and the number of comments
  • an optional responsive image

We’re using Flexbox here in order to “push” the information bar to the bottom. As a reminder, this is the article layout we’re aiming for:

Here’s the code:

<a class="article first-article"> <figure class="article-image"> <img  src="" alt="如何使用Flexbox构建新闻站点布局_html/css_WEB-ITnose" > </figure> <div class="article-body"> <h2 class="article-title"> <!-- title --> </h2> <p class="article-content"> <!-- content --> </p> <footer class="article-info"> <!-- information --> </footer> </div></a>

.article { display: flex; flex-direction: column; flex-basis: auto; /* sets initial element size based on its contents */}.article-body { display: flex; flex: 1; flex-direction: column;}.article-content { flex: 1; /* This will make the content fill up the remaining space, and thus push the information bar at the bottom */}

The article’s elements are laid out vertically thanks to the flex-direction: column; rule.

We apply flex: 1 to the article-content element so that it fills up the empty space, and “pushes” the article-info to the bottom, no matter the height of the columns.

4. Add Some Nested Columns

In the left column, what we actually want is another set of columns. So we’re going to replace the second article with the same columns container we’ve already used.

<div class="columns"> <div class="column nested-column"> <a class="article"> <!-- Article content --> </a> </div> <div class="column"> <a class="article"> <!-- Article content --> </a> <a class="article"> <!-- Article content --> </a> <a class="article"> <!-- Article content --> </a> </div></div>

As we want the first nested column to be wider, we’re adding a nested-column class with the additional style:

.nested-column { flex: 2;}

This will make our new column twice as wide as the other.

5. Give the First Article a Horizontal Layout

The first article is really big. To optimize the use of space, let’s switch its layout to be horizontal.

.first-article { flex-direction: row;}.first-article .article-body { flex: 1;}.first-article .article-image { height: 300px; order: 2; padding-top: 0; width: 400px;}

The order property is very useful here, as it allows us to alter the order of HTML elements without affecting the HTML markup. The article-image actually comes before the article-body in the markup, but it will behave as if it comes after.

6. Make the Layout Responsive

This is all looking just as we want, though it’s a bit squished. Let’s fix that by going responsive.

One great feature of Flexbox is that you need only remove the display: flex rule on the container to disable Flexbox completely, while keeping all the other Flexbox properties (such as align-items or flex) valid.

As a result, you can trigger a “responsive” layout by enabling Flexbox only above a certain breakpoint.

We’re going to remove display: flex from both the .columns and .column selectors, instead wrapping them in a media query:

@media screen and (min-width: 800px) { .columns, .column { display: flex; }}

That’s it! On smaller screens, all the articles will be on top of each other. Above 800px, they will be laid out in two columns.

7. Add Finishing Touches

To make the layout more appealing on larger screens, let’s add some CSS tweaks:

@media screen and (min-width: 1000px) { .first-article { flex-direction: row; } .first-article .article-body { flex: 1; } .first-article .article-image { height: 300px; order: 2; padding-top: 0; width: 400px; } .main-column { flex: 3; } .nested-column { flex: 2; }}

The first article has its content laid out horizontally, with the text on the left and the image on the right. Also, the main column is now wider (75%) and the nested column too (66%). Here’s the final result!

Conclusion

I hope I’ve shown you that you needn’t understand every aspect of Flexbox to jump in and start using it! This responsive news layout is a really useful pattern; pull it apart, play with it, let us know how you get on!

성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
HTML 태그가 웹 개발에 중요한 이유는 무엇입니까?HTML 태그가 웹 개발에 중요한 이유는 무엇입니까?May 02, 2025 am 12:03 AM

htmltagsareessentialforwebdevelopmentasthuctureandenhancewebpages.1) thefinelayout, semantics 및 internactivity.2) semantictagsimproveAccessibility 및 sseo.3) appleasoftagscanoptimizeperformanceandenseRocRossercompatiber.

HTML 태그 및 속성에 일관된 코딩 스타일을 사용하는 것의 중요성을 설명하십시오.HTML 태그 및 속성에 일관된 코딩 스타일을 사용하는 것의 중요성을 설명하십시오.May 01, 2025 am 12:01 AM

일관된 HTML 인코딩 스타일은 코드의 가독성, 유지 가능성 및 효율성을 향상시키기 때문에 중요합니다. 1) 소문자 태그 및 속성 사용, 2) 일관된 압입 유지, 3) 단일 또는 이중 인용문을 선택하고 고수하십시오. 4) 프로젝트에서 다양한 스타일을 혼합하지 않으십시오.

Bootstrap 4에서 멀티 프로 젝트 회전 목마를 구현하는 방법은 무엇입니까?Bootstrap 4에서 멀티 프로 젝트 회전 목마를 구현하는 방법은 무엇입니까?Apr 30, 2025 pm 03:24 PM

솔루션 Bootstrap4에서 다중 프로 젝트 회전 목마를 구현하는 것은 부트 스트랩 4에서 멀티 프로 젝트 회전 목마를 구현하는 것은 쉬운 일이 아닙니다. 부트 스트랩 ...

DeepSeek 공식 웹 사이트는 마우스 스크롤 이벤트를 관통하는 효과를 어떻게 달성합니까?DeepSeek 공식 웹 사이트는 마우스 스크롤 이벤트를 관통하는 효과를 어떻게 달성합니까?Apr 30, 2025 pm 03:21 PM

마우스 스크롤링 이벤트 침투의 효과를 달성하는 방법은 무엇입니까? 웹을 탐색하면 종종 특별한 상호 작용 디자인이 발생합니다. 예를 들어, DeepSeek 공식 웹 사이트에서 � ...

HTML 비디오의 재생 제어 스타일 수정 방법HTML 비디오의 재생 제어 스타일 수정 방법Apr 30, 2025 pm 03:18 PM

HTML 비디오의 기본 재생 제어 스타일은 CSS를 통해 직접 수정할 수 없습니다. 1. JavaScript를 사용하여 사용자 정의 컨트롤을 만듭니다. 2. CSS를 통해 이러한 통제를 아름답게합니다. 3. video.js 또는 plyr와 같은 라이브러리를 사용하여 호환성, 사용자 경험 및 성능을 고려하면 프로세스를 단순화 할 수 있습니다.

휴대 전화에서 기본 선택을 사용하면 어떤 문제가 발생합니까?휴대 전화에서 기본 선택을 사용하면 어떤 문제가 발생합니까?Apr 30, 2025 pm 03:15 PM

휴대 전화에서 기본 선택을 사용하는 데있어 잠재적 인 문제는 모바일 애플리케이션을 개발할 때 종종 상자를 선택해야 할 필요가 있습니다. 일반적으로 개발자 ...

휴대 전화에서 기본 선택을 사용하는 단점은 무엇입니까?휴대 전화에서 기본 선택을 사용하는 단점은 무엇입니까?Apr 30, 2025 pm 03:12 PM

휴대 전화에서 기본 선택을 사용하는 단점은 무엇입니까? 모바일 장치에서 애플리케이션을 개발할 때는 올바른 UI 구성 요소를 선택하는 것이 매우 중요합니다. 많은 개발자 ...

Three.js 및 Octree를 사용하여 방에서 3 인칭 로밍의 충돌 처리를 최적화하는 방법은 무엇입니까?Three.js 및 Octree를 사용하여 방에서 3 인칭 로밍의 충돌 처리를 최적화하는 방법은 무엇입니까?Apr 30, 2025 pm 03:09 PM

Three.js 및 Octree를 사용하여 방에서 3 인칭 로밍의 충돌 처리를 최적화하십시오. 3.js의 Octree를 사용하여 방에서 3 인칭 로밍을 구현하고 충돌을 추가하십시오 ...

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

SecList

SecList

SecLists는 최고의 보안 테스터의 동반자입니다. 보안 평가 시 자주 사용되는 다양한 유형의 목록을 한 곳에 모아 놓은 것입니다. SecLists는 보안 테스터에게 필요할 수 있는 모든 목록을 편리하게 제공하여 보안 테스트를 더욱 효율적이고 생산적으로 만드는 데 도움이 됩니다. 목록 유형에는 사용자 이름, 비밀번호, URL, 퍼징 페이로드, 민감한 데이터 패턴, 웹 셸 등이 포함됩니다. 테스터는 이 저장소를 새로운 테스트 시스템으로 간단히 가져올 수 있으며 필요한 모든 유형의 목록에 액세스할 수 있습니다.

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

Dreamweaver Mac版

Dreamweaver Mac版

시각적 웹 개발 도구