KE
  • dotNet Web 3.0
  • Engineering Management
    • Process Planning (SDLC)
      • Software development process
      • Basics of SDLC models
      • Scrum
      • Kanban
      • Scrum vs Kanban: applicability
      • Scrumban
    • Estimation
      • Scope Concept
      • Estimates, Targets, and Commitments
      • Overestimate vs Underestimate
      • Decomposition and Recomposition
      • Analogy-based estimations
      • Estimating in Agile
  • Requirements
    • Software Requirements Engineering
      • Requirement definition
      • Levels of Requirements
      • Most common requirements risks
      • Characteristics of Excellent Requirements
      • Benefits from a High-Quality Requirements Process
      • Root Causes of Project Success and Failure
  • Design
    • OOD
      • Abstraction
      • Encapsulation
      • Inheritance vs Aggregation
      • Modularity
      • Polymorphism
      • Abstraction Qualities (cohesion, coupling, etc)
      • Types vs. Classes
      • Separation of concerns principle
      • SOLID
      • Design Patterns
        • Structural patterns
        • Creational patterns
        • Behavioral patterns
      • Most often used design patterns
      • Software Architecture Patterns (structure, pros & cons)
      • Inversion of Control Containers and the Dependency Injection pattern
      • Domain-Driven Design patterns
      • Anti-patterns
    • DB Design
      • Relational Terminology: Entities
      • Relational terminology: Attributes
      • Relational terminology: Records (Tuples)
      • Relationships (One-to-One, One-to-Many)
      • Understanding ER notation
      • Understanding normalization concept
      • Data Integrity
    • Modeling
      • UML: Basic Diagram Types
      • UML: Use Case Diagram (Essentials)
      • UML: Class Diagram (Essentials)
      • Entity Relationship Diagrams
      • Data Flow Diagrams
    • Security
      • Information security concepts
      • Access Control Lists (ACLs)
      • Access Control Models
      • .NET Cryptography Model
      • ASP.NET Identity
      • OWASP Top 10
      • Cross-Site Request Forgery (XSRF)
      • Protecting against cross-site scripting attacks (XSS)
      • Protecting against buffer overrun attacks
      • Protecting against SQL-injection attacks
      • CSRF/XSRF protection
    • Algorithms
      • Algorithms complexity (understanding, big O notation, complexity of common algorithms)
      • Array sorting methods (bubble sort, quick sort, merge sort)
      • Tree structure (construction, traversal)
      • Binary search algorithm
      • Hash table (creating, collisions)
      • Stack, queue, linked list (construction, understanding, usage)
  • Construction Core
    • Programming language
      • Declare namespaces, classes, interfaces, static and instance class members
      • Types casting
      • Value and reference types. Class vs Struct usage.
      • Properties and automatic properties
      • Structured Exception Handling, Exception filters
      • Collections and Generics
      • Dictionaries. Comparison of Dictionaries
      • Building enumerable types
      • Building cloneable objects
      • Building comparable types
      • Nullable types
      • Delegates, events and lambdas
      • Indexers and operator overloading
      • Anonymous types
      • Extension methods. Practices.
      • Custom Type Conversions (implicit/explicit keywords)
      • Strings and StringBuilder. String concatenation practices. String Interpolation
      • Serialization
      • System.IO namespace
      • LINQ to Objects
      • General Coding conventions for C#
      • Static Using Statement
      • Type Reflection
      • Custom attributes
      • Dispose and Finalizable patterns
      • Garbage collection
      • .Net Diagnostics
      • Implementing logging
      • Exception handling guidelines
      • Regular Expressions
      • Span<T> struct
      • C# - What's new?
      • .NET Standard overview
    • Concurrency
      • Understand differences between Concurrency vs Multi-threading vs Asynchronous
      • Concurrency: An Overview
      • Async basics
      • Task Parallelism
      • Basic Synchronization in C#
      • Deadlock problem
      • QueueBackgroundWorkItem or IHostedService for .NET Core
      • How to run Background Tasks in ASP.NET
    • Refactoring
      • Refactoring Concept (what/when/why)
      • Smells Catalog and possible re-factorings
      • Moving Features Between Objects (basic)
      • Organizing Data (basic)
      • Composing Methods (basic)
      • Simplifying Conditional Expressions (basic)
      • Making Method Calls Simpler
      • Dealing with Generalization
    • Product deploying, software installation
      • Create, configure, and publish a web package (.NET Web Profile)
      • Publishing Web Services
      • Manage packages by using NuGet, NPM and Bower
    • Networking
      • Understanding networks: layers and protocols
      • Basic understanding of TCP/IP model and protocols
      • Defining internet, intranet and VPN
      • Basics of Firewalls and DMZ
      • Application layer protocols basics (HTTP, FTP, Telnet)
      • Understanding HTTP and WWW
      • Basic troubleshooting tools (ICMP, ping, traceroute)
      • Client/Server model
      • Sockets, IP and port addressing
      • Using proxy server
      • File transfer services: FTP, TFTP
      • Name resolution services: DNS, whois
      • Remote access services: Telnet, SSH, rdesktop, VNC
      • The basic difference between HTTP and HTTPS protocols
  • Construction Web
    • Web server applications
      • ASP.NET Core
        • Application startup
        • Middleware
        • Working with Static Files
        • Routing
        • Error Handling
        • Globalization and localization
        • Configuration
        • Logging
        • File Providers
        • Dependency Injection
        • Working with Multiple Environments
        • Hosting
        • Managing Application State
        • Request Features
      • ASP.NET Core MVC
        • MVC basics (Model, View, Controller, DI)
        • Model binding and validation
        • View (Razor compilation, Layout, Tag Helpers, Partial Views, DI, View components)
        • Controllers (Route to actions, File uploads)
      • Security and Identity (concepts understanding)
        • Authentication
        • Using identity
        • Authorization with roles
      • Bundle and Minify assets
      • Develop ASP.NET Core MVC apps
      • Advanced topics for ASP.NET Core MVC
        • Application model
        • Filters
        • Areas
        • Application Parts
        • Custom Model Building
        • IActionConstraint
      • Host and deploy ASP.NET Core
      • Migrate from ASP.NET to ASP.NET Core
      • Troubleshoot ASP.NET Core projects
      • Open Web Interface for .NET (OWIN)
      • Web server implementations in ASP.NET Core
    • Web Services
      • REST
      • ASP.NET Web API
        • Routing
        • Configuration
        • Basic error handling
      • Web API-based services
      • Web API Security
      • Token based security
      • SingalR
      • Serialization Frameworks
      • Implement caching
      • gRPC on ASP.NET Core
      • API versioning
      • API documentation
    • Microservices and Cloud
      • Microservices architecture
      • Dockerize a .NET Core application
      • Development workflow for Docker apps
    • JavaScript, HTML, CSS
      • JavaScript: Variables
      • JavaScript: Data types and types conversion
      • JavaScript: Operators
      • JavaScript: Control and Loop constructions
      • JavaScript: Functions, Execution Context and Variables scopes
      • JavaScript: Arrays
      • JavaScript: JS in WebBrowser and basic DOM manipulations
      • HTML: Basic elements
      • CSS: Simple Style rules
      • CSS: selectors
      • Box model
      • HTML: Standards and Browser compatibility
      • HTML: Page Layouts with divs
      • HTML: Frames
      • CSS: Elements positioning and layering
      • CSS: Tables properties
      • CSS: Flexbox
      • Different storage
      • JavaScript: Event Understanding (propagation, capturing, attach/detach)
      • JavaScript: Closure
      • AJAX/JSON
      • Ecma script 6: OOP
      • Promise
      • Strict mode of javascript
    • JavaScript Frameworks
      • Selecting elements
      • Operating on collection
      • Manipulating with elements, working with properties, attributes and data
      • Events
      • animation and effects
      • utilities and Ajax
      • SPA (SINGLE PAGE APPLICATIONS)
      • EcmaScript 6
      • UI frameworks basics:
      • NPM basics:
      • React basics
  • Construction DB
    • SQL
      • Tables, relationships, keys, constraints understanding
      • DDL, DML, DCL understanding
      • SQL data types
      • SQL operators, functions
      • Data manipulation (insert, update, delete)
      • Retrieving data (simple select statement)
      • Joins understanding
      • Creating, modifying, removing database objects
      • Aggregations (ORDER BY, GROUP BY, HAVING, SUM, COUNT, AVG, etc)
      • Combining the results of multiple queries (UNION, EXCEPT, INTERSECT, MINUS, subqueries)
      • Sessions, transactions, locks
      • Isolation levels understanding
      • Implementing stored procedures, user-defined functions, triggers
      • Cursors
    • Data Access Layer
      • Manage connection strings and objects
      • Working with data providers
      • Connect to a data source by using a generic data access interface
      • Handle and diagnose database connection exceptions
      • Manage exceptions when selecting, modifying data
      • Build command objects and query data from data sources
      • Retrieve data source by using the DataReader
      • Manage data by using the DataAdapter and TableAdapter
      • Updating data
      • Entity Framework
        • Query data sources by using EF
        • Code First to existing DB
        • Entity Data Modeling Fundamentals
        • Querying Data
        • Data modification
  • Verification
    • Code Quality
      • MSDN: Guidelines for Names
      • SDO Best Practices Catalog - Coding Standards
      • SDO Best Practices Catalog - Code Review Process
      • SDO Best Practices Catalog - Automatic Code Inspection
      • Automated coding standards enforcement (StyleCop, Resharper)
      • Code Reviews and Toolset
      • Use Work Items (TODO, BUG etc.)
      • Preemptive Error Detection
      • Desirable characteristics of a design (minimal complexity, ease of maintenance, minimal connectednes
      • Creating high quality classes
      • Creating high quality methods
      • Guidelines for initializing variables
      • Exceptions and error handling techniques
      • Best practices of working with data types
      • Code commenting practices
    • Automated Testing (principles, patterns, and practices)
      • Software testing basic concepts
      • Software testing concept
      • Test Case
      • Test Suite
      • Test Plan
      • Testing Levels
      • Naming standards for unit tests
      • Types of test doubles (Stub, Mock, Spy, Fake, Dummy)
      • Basic coverage criteria
      • Testing concepts (Unit vs Functional vs Integration)
      • Goals of Unit Testing, What Makes a Test Valuable?
      • Styles of Unit Testing (Output / State / Collaboration)
      • Good unit test properties
      • F.I.R.S.T Principles of unit testing
      • Test Pyramid concept
      • Testing Pyramid, Agile Testing Pyramid, Diamond
      • Breaking the dependency, Interaction testing
      • Strategies for isolating the database in tests
      • Test smells and how to avoid
      • Test Organization patterns
      • Fixture setup patterns
      • Test double patterns
      • Feature-driven development (FDD)
      • Behavior-driven development (BDD)
      • Test-driven development (TDD)
      • Acceptance testing, Acceptance Test Driven Development (ATDD)
      • Continuous testing
    • Automated Testing (Frameworks, Tools, Libraries)
      • .NET unit test frameworks overview
      • .NET Mocking Frameworks, a comparison
      • xUnit
        • Primary test framework attributes
        • Asserts
        • Exception Handling in Unit Tests
        • Skipping Tests
        • Initialization and Cleanup (Assembly, Class, Test)
        • Data-driven Tests
      • NSubstitute
        • Mocking Method Calls (Using Mock Object, Return Values, Argument Matching)
        • Behavior Verification (Method Was/Not Called, a Specific Number of Times, Getter/Setter Was Called)
        • Throwing exceptions
        • Raising Events from Mock Objects
        • Returning Different Results for Sequential Calls
      • AutoFixture
      • EF Core InMemory test
      • Integration tests in ASP.NET Core
      • Isolating database data in integration tests
      • Test ASP.NET Core MVC apps
  • Configuration Management
    • Product builds and Continuous Integration
      • Automated build concept
      • Dotnet cli
      • CI/CD Basic concepts
    • Managing Versions
      • Fundamental concepts: revisions, working copy, repository, branch, baseline, trunk
      • Versioning Models
      • Distributed Version Control basics
      • Distributed systems advantages and weak sides
      • VCS Management life-cycle on (one of) major tools (clone, commit, update, revert, merge, resolve, et
      • Branching/Merging strategies
      • Blaming (annotate)
      • Revision graph/log actions (Git)
      • Integrating with Issue Tracking Systems
      • Source control Best Practices
Powered by GitBook
On this page
  • flexbox overview
  • flex containers
  • aligning a flex item
  • grouping flex items
  • cross-axis (vertical) alignment
  • wrapping flex items
  • flex container direction
  • flex container order
  • flex item order
  • flex item alignment
  • flexible items
  • static item widths
  • summary
  1. Construction Web
  2. JavaScript, HTML, CSS

CSS: Flexbox

PreviousCSS: Tables propertiesNextDifferent storage

Last updated 5 years ago

The “Flexible Box” or “Flexbox” layout mode offers an alternative to for defining the overall appearance of a web page. Whereas floats only let us horizontally position our boxes, flexbox gives us complete control over the alignment, direction, order, and size of our boxes.

Diagram: comparison of flexbox alignment, direction, order, and size properties
Diagram: CSS floats for text wrapping around a box versus flexbox for the rest of the page layout

flexbox overview

Flexbox uses two types of boxes that we’ve never seen before: “flex containers” and “flex items”. The job of a flex container is to group a bunch of flex items together and define how they’re positioned.

flex containers

.menu-container {
  /* ... */
  display: flex;
}

aligning a flex item

After you’ve got a flex container, your next job is to define the horizontal alignment of its items.

.menu-container {
  /* ... */
  display: flex;
  justify-content: center;    /* Add this */
}

This has the same effect as adding a margin: 0 auto declaration to the .menu element. But, notice how we did this by adding a property to the parent element (the flex container) instead of directly to the element we wanted to center (the flex item). Manipulating items through their containers like this is a common theme in flexbox, and it’s a bit of a divergence from how we’ve been positioning boxes thus far.

Other values for justify-content are shown below:

  • center

  • flex-start

  • flex-end

  • space-around

  • space-between

Try changing justify-content to flex-start and flex-end. This should align the menu to the left and right side of the browser window, respectively. Be sure to change it back to center before moving on. The last two options are only useful when you have multiple flex items in a container.

grouping flex items

Flex containers only know how to position elements that are one level deep (i.e., their child elements). They don’t care one bit about what’s inside their flex items. This means that grouping flex items is another weapon in your layout-creation arsenal. Wrapping a bunch of items in an extra <div>results in a totally different web page.

<div class='menu'>
  <div class='date'>Aug 14, 2016</div>
  <div class='links'>
    <div class='signup'>Sign Up</div>      <!-- This is nested now -->
    <div class='login'>Login</div>         <!-- This one too! -->
  </div>
</div>
.links {
  border: 1px solid #fff;  /* For debugging */
  display: flex;
  justify-content: flex-end;
}

.login {
  margin-left: 20px;
}

cross-axis (vertical) alignment

his is something that’s simply not possible with floats.

The available options for align-items is similar to justify-content:

  • center

  • flex-start (top)

  • flex-end (bottom)

  • stretch

  • baseline

Most of these are pretty straightforward. The stretch option is worth a taking a minute to play with because it lets you display the background of each element. Let’s take a brief look by adding the following to styles.css:

.header {
  /* ... */
  align-items: stretch;    /* Change this */
}

wrapping flex items

To create a grid, we need the flex-wrap property.

.photo-grid {
  /* ... */
  flex-wrap: wrap;
}

flex container direction

“Direction” refers to whether a container renders its items horizontally or vertically. So far, all the containers we’ve seen use the default horizontal direction, which means items are drawn one after another in the same row before popping down to the next column when they run out of space.

Try adding the followingflex-direction declaration to our .photo-grid rule:

.photo-grid {
  /* ... */
  flex-direction: column;
}

alignment considerations

Notice that the column is hugging the left side of its flex container despite our justify-content: center; declaration. When you rotate the direction of a container, you also rotate the direction of the justify-contentproperty. It now refers to the container’s vertical alignment—not its horizontal alignment.

To horizontally center our column, we need to define an align-itemsproperty on our .photo-grid:

.photo-grid {
  /* ... */
  flex-direction: column;
  align-items: center;      /* Add this */
}

flex container order

The flex-direction property also offers you control over the order in which items appear via the row-reverse and column-reverse properties.

flex item order

This entire chapter has been about positioning flex items through their parent containers, but it’s also possible to manipulate individual items. The rest of this chapter is going to shift focus away from flex containers onto the items they contain.

flex item alignment

We can do the same thing with vertical alignment. What if we want thatSubscribe link and those social icons to go at the bottom of the header instead of the center? Align them individually! This is where the align-self property comes in. Adding this to a flex item overrides the align-items value from its container:

.social,
.subscribe {
  align-self: flex-end;
  margin-bottom: 20px;
}

This should send them to the bottom of the .header. Note that margins (padding, too) work just like you’d expect.

You can align elements in other ways using the same values as the align-items property, listed below for convenience.

  • center

  • flex-start (top)

  • flex-end (bottom)

  • stretch

  • baseline

flexible items

Flex items are flexible: they can shrink and stretch to match the width of their containers.

The flex property defines the width of individual items in a flex container. Or, more accurately, it allows them to have flexible widths. It works as a weight that tells the flex container how to distribute extra space to each item. For example, an item with a flex value of 2 will grow twice as fast as items with the default value of 1.

.footer {
  display: flex;
  justify-content: space-between;
}

.footer-item {
  border: 1px solid #fff;
  background-color: #D6E9FE;
  height: 200px;
  flex: 1;
}

That flex: 1; line tells the items to stretch to match the width of .footer. Since they all have the same weight, they’ll stretch equally:

Increasing the weight of one of the items makes it grow faster than the others. For example, we can make the third item grow twice as fast as the other two with the following rule:

.footer-three {
  flex: 2;
}

Compare this to the justify-content property, which distributes extra space between items. This is similar, but now we’re distributing that space into the items themselves. The result is full control over how flex items fit into their containers.

static item widths

We can even mix-and-match flexible boxes with fixed-width ones. flex: initial falls back to the item’s explicit width property. This lets us combine static and flexible boxes in complex ways.

We’re going to make our footer behave like the above diagram. The center item is flexible, but the ones on either side are always the same size. All we need to do is add the following rule to our stylesheet:

.footer-one,
.footer-three {
  background-color: #5995DA;
  flex: initial;
  width: 300px;
}

summary

  • Use display: flex; to create a flex container.

  • Use justify-content to define the horizontal alignment of items.

  • Use align-items to define the vertical alignment of items.

  • Use flex-direction if you need columns instead of rows.

  • Use the row-reverse or column-reverse values to flip item order.

  • Use order to customize the order of individual elements.

  • Use align-self to vertically align individual items.

  • Use flex to create flexible boxes that can stretch and shrink.

Diagram: flex container as a highlighted container wrapping grayed out elements versus flex items as highlighted boxes inside the container

This enables the flexbox layout mode—without it, the browser would ignore all the flexbox properties that we’re about to introduce. Explicitly defining flex containers means that you can mix and match flexbox with other layout models (e.g., floats and everything we’re going to learn in ).

Diagram: Mixing and matching flexbox layout with block boxes and floats
Diagram: flex-start (3 left-aligned boxes), center (3 center-aligned boxes), flex-end (3 right-aligned boxes)
Diagram: wrapping two flex items in a <div> to eliminate one of the flex items
Diagram: justify-content (left and right), align-items (top and bottom)
Diagram: flex-start (boxes at top of container), center (boxes in center of container), flex-end (boxes at bottom of container, stretch (boxes filling height of container)
Diagram: no wrapping (boxes flowing outside of container), with wrapping (boxes wrapping to next line in container)
Diagram: row (3 horizontal boxes), column (3 vertical boxes)
Diagram: axes flipped when flex-direction is equal to column
Diagram: row (left to right), row-reverse (right to left), column (top to bottom), column-reverse (bottom to top)
Diagram: setting the order of a flex item individual with the order property
Web page showing bottom-aligned icons via the align-self property
Diagram: no flex (3 square boxes), equal flex (3 rectangle boxes), unequal flex (2 smaller boxes, one stretched out box)
Web page with three equal boxes that stretch to fill the footer
Diagram: fixed-width box (flex: initial), flexible box (flex: 1)
Advanced Positioning
Floats