Rectangle 27 310

What's a container?

In Dockerland, there are images and there are containers. The two are closely related, but distinct. For me, grasping this dichotomy has clarified Docker immensely.

An image is an inert, immutable, file that's essentially a snapshot of a container. Images are created with the build command, and they'll produce a container when started with run. Images are stored in a Docker registry such as registry.hub.docker.com. Because they can become quite large, images are designed to be composed of layers of other images, allowing a miminal amount of data to be sent when transferring images over the network.

Local images can be listed by running docker images:

REPOSITORY                TAG                 IMAGE ID            CREATED             VIRTUAL SIZE
ubuntu                    13.10               5e019ab7bf6d        2 months ago        180 MB
ubuntu                    14.04               99ec81b80c55        2 months ago        266 MB
ubuntu                    latest              99ec81b80c55        2 months ago        266 MB
ubuntu                    trusty              99ec81b80c55        2 months ago        266 MB
<none>                    <none>              4ab0d9120985        3 months ago        486.5 MB
  • IMAGE ID is the first 12 characters of the true identifier for an image. You can create many tags of a given image, but their IDs will all be the same (as above).
  • VIRTUAL SIZE is virtual because its adding up the sizes of all the distinct underlying layers. This means that the sum of all the values in that column is probably much larger than the disk space used by all of those images.
  • The value in the REPOSITORY column comes from the -t flag of the docker build command, or from docker tag-ing an existing image. You're free to tag images using a nomenclature that makes sense to you, but know that docker will use the tag as the registry location in a docker push or docker pull.
[REGISTRYHOST/][USERNAME/]NAME[:TAG]
ubuntu
registry.hub.docker.com
my-application
docker.example.com
docker.example.com/my-application
  • The TAG column is just the [:TAG] part of the full tag. This is unfortunate terminology.
  • The latest tag is not magical, it's simply the default tag when you don't specify a tag.
  • You can have untagged images only identifiable by their IMAGE IDs. These will get the <none> TAG and REPOSITORY. It's easy to forget about them.

More info on images is available from the Docker docs and glossary.

To use a programming metaphor, if an image is a class, then a container is an instance of a classa runtime object. Containers are hopefully why you're using Docker; they're lightweight and portable encapsulations of an environment in which to run applications.

View local running containers with docker ps:

CONTAINER ID        IMAGE                               COMMAND                CREATED             STATUS              PORTS                    NAMES
f2ff1af05450        samalba/docker-registry:latest      /bin/sh -c 'exec doc   4 months ago        Up 12 weeks         0.0.0.0:5000->5000/tcp   docker-registry

Here I'm running a dockerized version of the docker registry, so that I have a private place to store my images. Again, some things to note:

  • Like IMAGE ID, CONTAINER ID is the true identifier for the container. It has the same form, but it identifies a different kind of object.
docker ps
docker ps -a
  • NAMES can be used to identify a started container via the --name flag.

One of my early frustrations with Docker was the seemingly constant buildup of untagged images and stopped containers. On a handful of occassions this buildup resulted in maxed out hard drives slowing down my laptop or halting my automated build pipeline. Talk about "containers everywhere"!

We can remove all untagged images by combining docker rmi with the recent dangling=true query:

docker images -q --filter "dangling=true" | xargs docker rmi

Docker won't be able to remove images that are behind existing containers, so you may have to remove stopped containers with docker rm first:

docker rm `docker ps --no-trunc -aq`

These are known pain points with Docker, and may be addressed in future releases. However, with a clear understanding of images and containers, these situations can be avoided with a couple of practices:

  • Always remove a useless, stopped container with docker rm [CONTAINER_ID].
  • Always remove the image behind a useless, stopped container with docker rmi [IMAGE_ID].

Good Differentiation bte images and container. Helps a lot for the beginners like me.

I guess what I'm stuck on is how images run (I use boot2docker on Windows). Why do we create images for applications, say mysql? At this point, how is mysql even running? Don't I need to have a Linux image to run mysql on top of?

Actually this isn't true: "docker pull-ing the :latest tag of an image will add at least two images to your local image list: one with the latest tag, and one for each original tag of the latest image, e.g. 14.04 and trysty above." It will only add one image with the latest tag. Pulling 14.04 later may be a no-op if the image ID is the same, but it still requires a separate pull.

This isn't true either: "The latest tag will always refer to the newest version of an image when specified in a docker pull.". The latest tag just refers to whatever was pushed with the tag latest. The wrinkle is that latest is used as the default tag if no tag is specified.

Docker image vs container - Stack Overflow

docker docker-container docker-image
Rectangle 27 323

What's a container?

In Dockerland, there are images and there are containers. The two are closely related, but distinct. For me, grasping this dichotomy has clarified Docker immensely.

An image is an inert, immutable, file that's essentially a snapshot of a container. Images are created with the build command, and they'll produce a container when started with run. Images are stored in a Docker registry such as registry.hub.docker.com. Because they can become quite large, images are designed to be composed of layers of other images, allowing a miminal amount of data to be sent when transferring images over the network.

Local images can be listed by running docker images:

REPOSITORY                TAG                 IMAGE ID            CREATED             VIRTUAL SIZE
ubuntu                    13.10               5e019ab7bf6d        2 months ago        180 MB
ubuntu                    14.04               99ec81b80c55        2 months ago        266 MB
ubuntu                    latest              99ec81b80c55        2 months ago        266 MB
ubuntu                    trusty              99ec81b80c55        2 months ago        266 MB
<none>                    <none>              4ab0d9120985        3 months ago        486.5 MB
  • IMAGE ID is the first 12 characters of the true identifier for an image. You can create many tags of a given image, but their IDs will all be the same (as above).
  • VIRTUAL SIZE is virtual because its adding up the sizes of all the distinct underlying layers. This means that the sum of all the values in that column is probably much larger than the disk space used by all of those images.
  • The value in the REPOSITORY column comes from the -t flag of the docker build command, or from docker tag-ing an existing image. You're free to tag images using a nomenclature that makes sense to you, but know that docker will use the tag as the registry location in a docker push or docker pull.
[REGISTRYHOST/][USERNAME/]NAME[:TAG]
ubuntu
registry.hub.docker.com
my-application
docker.example.com
docker.example.com/my-application
  • The TAG column is just the [:TAG] part of the full tag. This is unfortunate terminology.
  • The latest tag is not magical, it's simply the default tag when you don't specify a tag.
  • You can have untagged images only identifiable by their IMAGE IDs. These will get the <none> TAG and REPOSITORY. It's easy to forget about them.

More info on images is available from the Docker docs and glossary.

To use a programming metaphor, if an image is a class, then a container is an instance of a classa runtime object. Containers are hopefully why you're using Docker; they're lightweight and portable encapsulations of an environment in which to run applications.

View local running containers with docker ps:

CONTAINER ID        IMAGE                               COMMAND                CREATED             STATUS              PORTS                    NAMES
f2ff1af05450        samalba/docker-registry:latest      /bin/sh -c 'exec doc   4 months ago        Up 12 weeks         0.0.0.0:5000->5000/tcp   docker-registry

Here I'm running a dockerized version of the docker registry, so that I have a private place to store my images. Again, some things to note:

  • Like IMAGE ID, CONTAINER ID is the true identifier for the container. It has the same form, but it identifies a different kind of object.
docker ps
docker ps -a
  • NAMES can be used to identify a started container via the --name flag.

One of my early frustrations with Docker was the seemingly constant buildup of untagged images and stopped containers. On a handful of occassions this buildup resulted in maxed out hard drives slowing down my laptop or halting my automated build pipeline. Talk about "containers everywhere"!

We can remove all untagged images by combining docker rmi with the recent dangling=true query:

docker images -q --filter "dangling=true" | xargs docker rmi

Docker won't be able to remove images that are behind existing containers, so you may have to remove stopped containers with docker rm first:

docker rm `docker ps --no-trunc -aq`

These are known pain points with Docker, and may be addressed in future releases. However, with a clear understanding of images and containers, these situations can be avoided with a couple of practices:

  • Always remove a useless, stopped container with docker rm [CONTAINER_ID].
  • Always remove the image behind a useless, stopped container with docker rmi [IMAGE_ID].

Good Differentiation bte images and container. Helps a lot for the beginners like me.

I guess what I'm stuck on is how images run (I use boot2docker on Windows). Why do we create images for applications, say mysql? At this point, how is mysql even running? Don't I need to have a Linux image to run mysql on top of?

Actually this isn't true: "docker pull-ing the :latest tag of an image will add at least two images to your local image list: one with the latest tag, and one for each original tag of the latest image, e.g. 14.04 and trysty above." It will only add one image with the latest tag. Pulling 14.04 later may be a no-op if the image ID is the same, but it still requires a separate pull.

This isn't true either: "The latest tag will always refer to the newest version of an image when specified in a docker pull.". The latest tag just refers to whatever was pushed with the tag latest. The wrinkle is that latest is used as the default tag if no tag is specified.

Docker image vs container - Stack Overflow

docker docker-container docker-image
Rectangle 27 623

Note on docker container networking modes

Docker offers different networking modes when running containers. Depending on the mode you choose you would connect to your MySQL database running on the docker host differently.

Docker creates a bridge named docker0 by default. Both the docker host and the docker containers have an IP address on that bridge.

on the Docker host, type sudo ip addr show docker0 you will have an output looking like:

[vagrant@docker:~] $ sudo ip addr show docker0
4: docker0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default
    link/ether 56:84:7a:fe:97:99 brd ff:ff:ff:ff:ff:ff
    inet 172.17.42.1/16 scope global docker0
       valid_lft forever preferred_lft forever
    inet6 fe80::5484:7aff:fefe:9799/64 scope link
       valid_lft forever preferred_lft forever

So here my docker host has the IP address 172.17.42.1 on the docker0 network interface.

Now start a new container and get a shell on it: docker run --rm -it ubuntu:trusty bash -il and within the container type ip addr show eth0 to discover how its main network interface is set up:

root@e77f6a1b3740:/# ip addr show eth0
863: eth0: <BROADCAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
    link/ether 66:32:13:f0:f1:e3 brd ff:ff:ff:ff:ff:ff
    inet 172.17.1.192/16 scope global eth0
       valid_lft forever preferred_lft forever
    inet6 fe80::6432:13ff:fef0:f1e3/64 scope link
       valid_lft forever preferred_lft forever

Here my container has the IP address 172.17.1.192. Now look at the routing table:

root@e77f6a1b3740:/# route
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
default         172.17.42.1     0.0.0.0         UG    0      0        0 eth0
172.17.0.0      *               255.255.0.0     U     0      0        0 eth0

So the IP Address of the docker host 172.17.42.1 is set as the default route and is accessible from your container.

root@e77f6a1b3740:/# ping 172.17.42.1
PING 172.17.42.1 (172.17.42.1) 56(84) bytes of data.
64 bytes from 172.17.42.1: icmp_seq=1 ttl=64 time=0.070 ms
64 bytes from 172.17.42.1: icmp_seq=2 ttl=64 time=0.201 ms
64 bytes from 172.17.42.1: icmp_seq=3 ttl=64 time=0.116 ms

Alternatively you can run a docker container with network settings set to host. Such a container will share the network stack with the docker host and from the container point of view, localhost (or 127.0.0.1) will refer to the docker host.

Be aware that any port opened in your docker container would be opened on the docker host. And this without requiring the -p or -P docker run option.

[vagrant@docker:~] $ ip addr show eth0
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
    link/ether 08:00:27:98:dc:aa brd ff:ff:ff:ff:ff:ff
    inet 10.0.2.15/24 brd 10.0.2.255 scope global eth0
       valid_lft forever preferred_lft forever
    inet6 fe80::a00:27ff:fe98:dcaa/64 scope link
       valid_lft forever preferred_lft forever

and from a docker container in host mode:

[vagrant@docker:~] $ docker run --rm -it --net=host ubuntu:trusty ip addr show eth0
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
    link/ether 08:00:27:98:dc:aa brd ff:ff:ff:ff:ff:ff
    inet 10.0.2.15/24 brd 10.0.2.255 scope global eth0
       valid_lft forever preferred_lft forever
    inet6 fe80::a00:27ff:fe98:dcaa/64 scope link
       valid_lft forever preferred_lft forever

As you can see both the docker host and docker container share the exact same network interface and as such have the same IP address.

bind-address = 172.17.42.1
bind-address = 0.0.0.0

If you need to set an environment variable with the IP address of the gateway, you can run the following code in a container :

export DOCKER_HOST_IP=$(route -n | awk '/UG[ \t]/{print $2}')

then in your application, use the DOCKER_HOST_IP environment variable to open the connection to MySQL.

Note: if you use bind-address = 0.0.0.0 your MySQL server will listen for connections on all network interfaces. That means your MySQL server could be reached from the Internet ; make sure to setup firewall rules accordingly.

Note 2: if you use bind-address = 172.17.42.1 your MySQL server won't listen for connections made to 127.0.0.1. Processes running on the docker host that would want to connect to MySQL would have to use the 172.17.42.1 IP address.

To access MySQL running on the docker host from containers in host mode, you can keep bind-address = 127.0.0.1 in your MySQL configuration and all you need to do is to connect to 127.0.0.1 from your containers:

[vagrant@docker:~] $ docker run --rm -it --net=host mysql mysql -h 127.0.0.1 -uroot -p
Enter password:
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 36
Server version: 5.5.41-0ubuntu0.14.04.1 (Ubuntu)

Copyright (c) 2000, 2014, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its affiliates. Other names may be trademarks of their respective owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql>

note: Do use mysql -h 127.0.0.1 and not mysql -h localhost; otherwise the MySQL client would try to connect using a unix socket.

Thank you for such a detailed answer! From what I've gathered, using host mode is the only way to get this functionality through localhost. I haven't tried but I would assume you could create a separate network to connect containers over their own bridge offering them a common 'localhost'.

Note for OSX users: log into your docker virtual machine first (boot2docker), using "docker-machine ssh default" , then run "sudo ip addr show docker0". Continue with Thomas' instructions from there.

I am running Docker for Mac, and there is no 172.17.42.1 anymore, no docker0 anymore. It was 172.17.0.1 as gateway, and can't even telnet 172.17.0.1 3306

You can mount the mysql socket into the container instead of networking like -v /var/run/mysqld/mysqld.sock:/tmp/mysql.sock this.

Can someone address the situation when your running Docker on Mac and not using boot2docker as such there is no docker0 interface?

nginx - From inside of a Docker container, how do I connect to the loc...

nginx docker reverse-proxy docker-networking
Rectangle 27 983

Container with overflow: auto;

Depending upon the design being produced, each of the below clearfix CSS solutions has its own benefits.

The clearfix does have useful applications but it has also been used as a hack. Before you use a clearfix perhaps these modern css solutions can be useful:

The simplest way to clear floated elements is using the style overflow: auto on the containing element. This solution works in every modern browsers.

<div style="overflow: auto;">
  <img
    style="float: right;"
    src="path/to/floated-element.png"
    width="500"
    height="500"
  > 
  <p>Your content here</p>
</div>

One downside, using certain combinations of margin and padding on the external element can cause scrollbars to appear but this can be solved by placing the margin and padding on another parent containing element.

Using overflow: hidden is also a clearfix solution, but will not have scrollbars, however using hidden will crop any content positioned outside of the containing element.

Note: The floated element is an img tag in this example, but could be any html element.

Thierry Koblentz on CSSMojo wrote: The very latest clearfix reloaded. He noted that by dropping support for oldIE, the solution can be simplified to one css statement. Additionally, using display: block (instead of display: table) allows margins to collapse properly when elements with clearfix are siblings.

.container::after {
  content: "";
  display: block;
  clear: both;
}

This is the most modern version of the clearfix.

The below solutions are not necessary for modern browsers, but may be useful for targeting older browsers.

Note that these solutions rely upon browser bugs and therefore should be used only if none of the above solutions work for you.

They are listed roughly in chronological order.

Thierry Koblentz' of CSS Mojo has pointed out that when targeting modern browsers, we can now drop the zoom and ::before property/values and simply use:

.container::after {
    content: "";
    display: table;
    clear: both;
}

Thierry also offers: "A word of caution: if you start a new project from scratch, go for it, but dont swap this technique with the one you have now, because even though you do not support oldIE, your existing rules prevent collapsing margins."

The most recent and globally adopted clearfix solution, the Micro Clearfix by Nicolas Gallagher.

.container::before, .container::after {
  content: "";
  display: table;
}
.container::after {
  clear: both;
}
.container {
  zoom: 1;
}

This basic method is preferred for the usual case, when positioned content will not show outside the bounds of the container.

width: 100%

Rather than using the display property to set "hasLayout" for IE, other properties can be used for triggering "hasLayout" for an element.

.container {
  overflow: hidden;
  zoom: 1;
  display: block;
}

Another way to clear floats using the overflow property is to use the underscore hack. IE will apply the values prefixed with the underscore, other browsers will not. The zoom property triggers hasLayout in IE:

.container {
  overflow: hidden;
  _overflow: visible; /* for IE */
  _zoom: 1; /* for IE */
}

While this works... it is not ideal to use hacks.

This older "Easy Clearing" method has the advantage of allowing positioned elements to hang outside the bounds of the container, at the expense of more tricky CSS.

This solution is quite old, but you can learn all about Easy Clearing on Position Is Everything: http://www.positioniseverything.net/easyclearing.html

The quick and dirty solution with many drawbacks:

<br style="clear: both" /> <!-- So dirty! -->
  • It's not responsive and thus may not provide the desired effect if layout styles change based upon media queries. A solution in pure CSS is more ideal.
  • In the future when you need to use another clearfix solution, you won't have to go back and remove every <br> tag littered around the markup.

+1 for explaining why the "overflow: hidden" method isn't perfect for all situations.

@David Rivers: The :after method is not a hack as it doesn't exploit a parsing error in a browser, it uses a feature of css as a solution. Additionally :after will be supported in future browsers, unlike the underscore hack. Ideally there will be a css property that can be applied to an element which will cause it to contain all it's content.

Thanks for the breakdown. I find the :after "easy clearing" method superior to "overflow: hidden", as it doesn't crop CSS3 box shadows or positioned elements. The extra lines of code are definitely worth it.

I'm not advocating the br clear:both solution, but I disagree with your 'dirty' labeling of it. The 'adding weight/load slower' argument seems silly, as it's 1 short line of html code, compared to the several lines of CSS (which your browser has to load too). For the 'semantic value' argument, a br with clear:both is far easier to understand than trying to figure out a bunch of goofy firing squad css. br clear:both is short and simple, and imho has no effect on 'professionalism'.

Contrary to popular belief, overflow: hidden or overflow: auto doesn't clear floats (categorizing it as "clearfix" is a misnomer); instead it causes an element to create a new formatting context within which the floats can be contained. This causes the container to stretch to the height of the floats in order to contain them. There is no clearance involved whatsoever - that being said, you can still choose to clear, or not clear, the floats within the container depending on your layout.

css - What methods of ‘clearfix’ can I use? - Stack Overflow

css clearfix
Rectangle 27 983

Container with overflow: auto;

Depending upon the design being produced, each of the below clearfix CSS solutions has its own benefits.

The clearfix does have useful applications but it has also been used as a hack. Before you use a clearfix perhaps these modern css solutions can be useful:

The simplest way to clear floated elements is using the style overflow: auto on the containing element. This solution works in every modern browsers.

<div style="overflow: auto;">
  <img
    style="float: right;"
    src="path/to/floated-element.png"
    width="500"
    height="500"
  > 
  <p>Your content here</p>
</div>

One downside, using certain combinations of margin and padding on the external element can cause scrollbars to appear but this can be solved by placing the margin and padding on another parent containing element.

Using overflow: hidden is also a clearfix solution, but will not have scrollbars, however using hidden will crop any content positioned outside of the containing element.

Note: The floated element is an img tag in this example, but could be any html element.

Thierry Koblentz on CSSMojo wrote: The very latest clearfix reloaded. He noted that by dropping support for oldIE, the solution can be simplified to one css statement. Additionally, using display: block (instead of display: table) allows margins to collapse properly when elements with clearfix are siblings.

.container::after {
  content: "";
  display: block;
  clear: both;
}

This is the most modern version of the clearfix.

The below solutions are not necessary for modern browsers, but may be useful for targeting older browsers.

Note that these solutions rely upon browser bugs and therefore should be used only if none of the above solutions work for you.

They are listed roughly in chronological order.

Thierry Koblentz' of CSS Mojo has pointed out that when targeting modern browsers, we can now drop the zoom and ::before property/values and simply use:

.container::after {
    content: "";
    display: table;
    clear: both;
}

Thierry also offers: "A word of caution: if you start a new project from scratch, go for it, but dont swap this technique with the one you have now, because even though you do not support oldIE, your existing rules prevent collapsing margins."

The most recent and globally adopted clearfix solution, the Micro Clearfix by Nicolas Gallagher.

.container::before, .container::after {
  content: "";
  display: table;
}
.container::after {
  clear: both;
}
.container {
  zoom: 1;
}

This basic method is preferred for the usual case, when positioned content will not show outside the bounds of the container.

width: 100%

Rather than using the display property to set "hasLayout" for IE, other properties can be used for triggering "hasLayout" for an element.

.container {
  overflow: hidden;
  zoom: 1;
  display: block;
}

Another way to clear floats using the overflow property is to use the underscore hack. IE will apply the values prefixed with the underscore, other browsers will not. The zoom property triggers hasLayout in IE:

.container {
  overflow: hidden;
  _overflow: visible; /* for IE */
  _zoom: 1; /* for IE */
}

While this works... it is not ideal to use hacks.

This older "Easy Clearing" method has the advantage of allowing positioned elements to hang outside the bounds of the container, at the expense of more tricky CSS.

This solution is quite old, but you can learn all about Easy Clearing on Position Is Everything: http://www.positioniseverything.net/easyclearing.html

The quick and dirty solution with many drawbacks:

<br style="clear: both" /> <!-- So dirty! -->
  • It's not responsive and thus may not provide the desired effect if layout styles change based upon media queries. A solution in pure CSS is more ideal.
  • In the future when you need to use another clearfix solution, you won't have to go back and remove every <br> tag littered around the markup.

+1 for explaining why the "overflow: hidden" method isn't perfect for all situations.

@David Rivers: The :after method is not a hack as it doesn't exploit a parsing error in a browser, it uses a feature of css as a solution. Additionally :after will be supported in future browsers, unlike the underscore hack. Ideally there will be a css property that can be applied to an element which will cause it to contain all it's content.

Thanks for the breakdown. I find the :after "easy clearing" method superior to "overflow: hidden", as it doesn't crop CSS3 box shadows or positioned elements. The extra lines of code are definitely worth it.

I'm not advocating the br clear:both solution, but I disagree with your 'dirty' labeling of it. The 'adding weight/load slower' argument seems silly, as it's 1 short line of html code, compared to the several lines of CSS (which your browser has to load too). For the 'semantic value' argument, a br with clear:both is far easier to understand than trying to figure out a bunch of goofy firing squad css. br clear:both is short and simple, and imho has no effect on 'professionalism'.

Contrary to popular belief, overflow: hidden or overflow: auto doesn't clear floats (categorizing it as "clearfix" is a misnomer); instead it causes an element to create a new formatting context within which the floats can be contained. This causes the container to stretch to the height of the floats in order to contain them. There is no clearance involved whatsoever - that being said, you can still choose to clear, or not clear, the floats within the container depending on your layout.

css - What methods of ‘clearfix’ can I use? - Stack Overflow

css clearfix
Rectangle 27 981

Container with overflow: auto;

Depending upon the design being produced, each of the below clearfix CSS solutions has its own benefits.

The clearfix does have useful applications but it has also been used as a hack. Before you use a clearfix perhaps these modern css solutions can be useful:

The simplest way to clear floated elements is using the style overflow: auto on the containing element. This solution works in every modern browsers.

<div style="overflow: auto;">
  <img
    style="float: right;"
    src="path/to/floated-element.png"
    width="500"
    height="500"
  > 
  <p>Your content here</p>
</div>

One downside, using certain combinations of margin and padding on the external element can cause scrollbars to appear but this can be solved by placing the margin and padding on another parent containing element.

Using overflow: hidden is also a clearfix solution, but will not have scrollbars, however using hidden will crop any content positioned outside of the containing element.

Note: The floated element is an img tag in this example, but could be any html element.

Thierry Koblentz on CSSMojo wrote: The very latest clearfix reloaded. He noted that by dropping support for oldIE, the solution can be simplified to one css statement. Additionally, using display: block (instead of display: table) allows margins to collapse properly when elements with clearfix are siblings.

.container::after {
  content: "";
  display: block;
  clear: both;
}

This is the most modern version of the clearfix.

The below solutions are not necessary for modern browsers, but may be useful for targeting older browsers.

Note that these solutions rely upon browser bugs and therefore should be used only if none of the above solutions work for you.

They are listed roughly in chronological order.

Thierry Koblentz' of CSS Mojo has pointed out that when targeting modern browsers, we can now drop the zoom and ::before property/values and simply use:

.container::after {
    content: "";
    display: table;
    clear: both;
}

Thierry also offers: "A word of caution: if you start a new project from scratch, go for it, but dont swap this technique with the one you have now, because even though you do not support oldIE, your existing rules prevent collapsing margins."

The most recent and globally adopted clearfix solution, the Micro Clearfix by Nicolas Gallagher.

.container::before, .container::after {
  content: "";
  display: table;
}
.container::after {
  clear: both;
}
.container {
  zoom: 1;
}

This basic method is preferred for the usual case, when positioned content will not show outside the bounds of the container.

width: 100%

Rather than using the display property to set "hasLayout" for IE, other properties can be used for triggering "hasLayout" for an element.

.container {
  overflow: hidden;
  zoom: 1;
  display: block;
}

Another way to clear floats using the overflow property is to use the underscore hack. IE will apply the values prefixed with the underscore, other browsers will not. The zoom property triggers hasLayout in IE:

.container {
  overflow: hidden;
  _overflow: visible; /* for IE */
  _zoom: 1; /* for IE */
}

While this works... it is not ideal to use hacks.

This older "Easy Clearing" method has the advantage of allowing positioned elements to hang outside the bounds of the container, at the expense of more tricky CSS.

This solution is quite old, but you can learn all about Easy Clearing on Position Is Everything: http://www.positioniseverything.net/easyclearing.html

The quick and dirty solution with many drawbacks:

<br style="clear: both" /> <!-- So dirty! -->
  • It's not responsive and thus may not provide the desired effect if layout styles change based upon media queries. A solution in pure CSS is more ideal.
  • In the future when you need to use another clearfix solution, you won't have to go back and remove every <br> tag littered around the markup.

+1 for explaining why the "overflow: hidden" method isn't perfect for all situations.

@David Rivers: The :after method is not a hack as it doesn't exploit a parsing error in a browser, it uses a feature of css as a solution. Additionally :after will be supported in future browsers, unlike the underscore hack. Ideally there will be a css property that can be applied to an element which will cause it to contain all it's content.

Thanks for the breakdown. I find the :after "easy clearing" method superior to "overflow: hidden", as it doesn't crop CSS3 box shadows or positioned elements. The extra lines of code are definitely worth it.

I'm not advocating the br clear:both solution, but I disagree with your 'dirty' labeling of it. The 'adding weight/load slower' argument seems silly, as it's 1 short line of html code, compared to the several lines of CSS (which your browser has to load too). For the 'semantic value' argument, a br with clear:both is far easier to understand than trying to figure out a bunch of goofy firing squad css. br clear:both is short and simple, and imho has no effect on 'professionalism'.

Contrary to popular belief, overflow: hidden or overflow: auto doesn't clear floats (categorizing it as "clearfix" is a misnomer); instead it causes an element to create a new formatting context within which the floats can be contained. This causes the container to stretch to the height of the floats in order to contain them. There is no clearance involved whatsoever - that being said, you can still choose to clear, or not clear, the floats within the container depending on your layout.

css - What methods of ‘clearfix’ can I use? - Stack Overflow

css clearfix
Rectangle 27 981

Container with overflow: auto;

Depending upon the design being produced, each of the below clearfix CSS solutions has its own benefits.

The clearfix does have useful applications but it has also been used as a hack. Before you use a clearfix perhaps these modern css solutions can be useful:

The simplest way to clear floated elements is using the style overflow: auto on the containing element. This solution works in every modern browsers.

<div style="overflow: auto;">
  <img
    style="float: right;"
    src="path/to/floated-element.png"
    width="500"
    height="500"
  > 
  <p>Your content here</p>
</div>

One downside, using certain combinations of margin and padding on the external element can cause scrollbars to appear but this can be solved by placing the margin and padding on another parent containing element.

Using overflow: hidden is also a clearfix solution, but will not have scrollbars, however using hidden will crop any content positioned outside of the containing element.

Note: The floated element is an img tag in this example, but could be any html element.

Thierry Koblentz on CSSMojo wrote: The very latest clearfix reloaded. He noted that by dropping support for oldIE, the solution can be simplified to one css statement. Additionally, using display: block (instead of display: table) allows margins to collapse properly when elements with clearfix are siblings.

.container::after {
  content: "";
  display: block;
  clear: both;
}

This is the most modern version of the clearfix.

The below solutions are not necessary for modern browsers, but may be useful for targeting older browsers.

Note that these solutions rely upon browser bugs and therefore should be used only if none of the above solutions work for you.

They are listed roughly in chronological order.

Thierry Koblentz' of CSS Mojo has pointed out that when targeting modern browsers, we can now drop the zoom and ::before property/values and simply use:

.container::after {
    content: "";
    display: table;
    clear: both;
}

Thierry also offers: "A word of caution: if you start a new project from scratch, go for it, but dont swap this technique with the one you have now, because even though you do not support oldIE, your existing rules prevent collapsing margins."

The most recent and globally adopted clearfix solution, the Micro Clearfix by Nicolas Gallagher.

.container::before, .container::after {
  content: "";
  display: table;
}
.container::after {
  clear: both;
}
.container {
  zoom: 1;
}

This basic method is preferred for the usual case, when positioned content will not show outside the bounds of the container.

width: 100%

Rather than using the display property to set "hasLayout" for IE, other properties can be used for triggering "hasLayout" for an element.

.container {
  overflow: hidden;
  zoom: 1;
  display: block;
}

Another way to clear floats using the overflow property is to use the underscore hack. IE will apply the values prefixed with the underscore, other browsers will not. The zoom property triggers hasLayout in IE:

.container {
  overflow: hidden;
  _overflow: visible; /* for IE */
  _zoom: 1; /* for IE */
}

While this works... it is not ideal to use hacks.

This older "Easy Clearing" method has the advantage of allowing positioned elements to hang outside the bounds of the container, at the expense of more tricky CSS.

This solution is quite old, but you can learn all about Easy Clearing on Position Is Everything: http://www.positioniseverything.net/easyclearing.html

The quick and dirty solution with many drawbacks:

<br style="clear: both" /> <!-- So dirty! -->
  • It's not responsive and thus may not provide the desired effect if layout styles change based upon media queries. A solution in pure CSS is more ideal.
  • In the future when you need to use another clearfix solution, you won't have to go back and remove every <br> tag littered around the markup.

+1 for explaining why the "overflow: hidden" method isn't perfect for all situations.

@David Rivers: The :after method is not a hack as it doesn't exploit a parsing error in a browser, it uses a feature of css as a solution. Additionally :after will be supported in future browsers, unlike the underscore hack. Ideally there will be a css property that can be applied to an element which will cause it to contain all it's content.

Thanks for the breakdown. I find the :after "easy clearing" method superior to "overflow: hidden", as it doesn't crop CSS3 box shadows or positioned elements. The extra lines of code are definitely worth it.

I'm not advocating the br clear:both solution, but I disagree with your 'dirty' labeling of it. The 'adding weight/load slower' argument seems silly, as it's 1 short line of html code, compared to the several lines of CSS (which your browser has to load too). For the 'semantic value' argument, a br with clear:both is far easier to understand than trying to figure out a bunch of goofy firing squad css. br clear:both is short and simple, and imho has no effect on 'professionalism'.

Contrary to popular belief, overflow: hidden or overflow: auto doesn't clear floats (categorizing it as "clearfix" is a misnomer); instead it causes an element to create a new formatting context within which the floats can be contained. This causes the container to stretch to the height of the floats in order to contain them. There is no clearance involved whatsoever - that being said, you can still choose to clear, or not clear, the floats within the container depending on your layout.

css - What methods of ‘clearfix’ can I use? - Stack Overflow

css clearfix
Rectangle 27 150

Center in container

override func viewDidLoad() {
    super.viewDidLoad()

    let myView = UIView()
    myView.backgroundColor = UIColor.blue
    myView.translatesAutoresizingMaskIntoConstraints = false
    view.addSubview(myView)

    // Add constraints code here
    // ...
}

Each of the following examples are independent of the others.

myView.leading = leadingMargin + 20
let margins = view.layoutMarginsGuide
myView.leadingAnchor.constraint(equalTo: margins.leadingAnchor, constant: 20).isActive = true
leadingAnchor
trailingAnchor
topAnchor
bottomAnchor
.leading
.trailing
.top
.bottom
.leadingMargin
.trailingMargin
.topMargin
.bottomMargin
width = 200
height = 100
myView.widthAnchor.constraint(equalToConstant: 200).isActive = true
myView.heightAnchor.constraint(equalToConstant: 100).isActive = true
NSLayoutConstraint(item: myView, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: 200).isActive = true
NSLayoutConstraint(item: myView, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: 100).isActive = true
myView.centerX = centerX
myView.centerY = centerY
myView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
myView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
NSLayoutConstraint(item: myView, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: NSLayoutAttribute.centerX, multiplier: 1, constant: 0).isActive = true
NSLayoutConstraint(item: myView, attribute: NSLayoutAttribute.centerY, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: NSLayoutAttribute.centerY, multiplier: 1, constant: 0).isActive = true
  • Anchor style is the preferred method over NSLayoutConstraint Style, however it is only available from iOS 9, so if you are supporting iOS 8 then you should still use NSLayoutConstraint Style.
  • The examples above showed just the one or two constraints that were being focused on. However, in order to properly place myView in my test project I needed to have four constraints.
leading
centerX

@CyberDude, yes, you are correct. I meant for all of the examples above to be independent of each other, not adding all of the constraints to the same view. That is not as clear as I would have liked, though.

You left out the necessary addConstraint() on view in order to make the layoutconstraints register.

isActive = true

ios - Swift | Adding constraints programmatically - Stack Overflow

ios xcode swift uiview autolayout
Rectangle 27 23

Center in container

The code below does the same thing as centering in the Interface Builder.

override func viewDidLoad() {
    super.viewDidLoad()

    // set up the view
    let myView = UIView()
    myView.backgroundColor = UIColor.blue
    myView.translatesAutoresizingMaskIntoConstraints = false
    view.addSubview(myView)

    // Add code for one of the constraint methods below
    // ...
}
myView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
myView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
NSLayoutConstraint(item: myView, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0).active = true
NSLayoutConstraint(item: myView, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0).active = true
  • Anchor style is the preferred method over NSLayoutConstraint Style, however it is only available from iOS 9, so if you are supporting iOS 8 then you should still use NSLayoutConstraint Style.

ios - Programmatically Add CenterX/CenterY Constraints - Stack Overflo...

ios xcode swift autolayout nslayoutconstraint
Rectangle 27 18

The container :

text-align : center;
.container {
  width: 100%;
  height: 120px;
  background: #ccc;
  text-align: center;
}

.centered-content {
  display: inline-block;
  background: #fff;
  padding: 20px;
  border: 1px solid #000;
}
<div class="container">
  <div class="centered-content">
    Center this!
  </div>
</div>

In my experience, the best way to center a box both vertically and horizontally, is to use an additional container and apply the following properties :

display: table;
display: table-cell;
vertical-align: middle;
text-align: center;
display: inline-block;
.outer-container {
  display: table;
  width: 100%;
  height: 120px;
  background: #ccc;
}

.inner-container {
  display: table-cell;
  vertical-align: middle;
  text-align: center;
}

.centered-content {
  display: inline-block;
  background: #fff;
  padding: 20px;
  border: 1px solid #000;
}
<div class="outer-container">
  <div class="inner-container">
    <div class="centered-content">
      Center this!
    </div>
  </div>
</div>

html - How to horizontally center a
in another
? - Stack Ov...

html css alignment
Rectangle 27 18

The container :

text-align : center;
.container {
  width: 100%;
  height: 120px;
  background: #ccc;
  text-align: center;
}

.centered-content {
  display: inline-block;
  background: #fff;
  padding: 20px;
  border: 1px solid #000;
}
<div class="container">
  <div class="centered-content">
    Center this!
  </div>
</div>

In my experience, the best way to center a box both vertically and horizontally, is to use an additional container and apply the following properties :

display: table;
display: table-cell;
vertical-align: middle;
text-align: center;
display: inline-block;
.outer-container {
  display: table;
  width: 100%;
  height: 120px;
  background: #ccc;
}

.inner-container {
  display: table-cell;
  vertical-align: middle;
  text-align: center;
}

.centered-content {
  display: inline-block;
  background: #fff;
  padding: 20px;
  border: 1px solid #000;
}
<div class="outer-container">
  <div class="inner-container">
    <div class="centered-content">
      Center this!
    </div>
  </div>
</div>

html - How to horizontally center a
in another
? - Stack Ov...

html css alignment
Rectangle 27 18

The container :

text-align : center;
.container {
  width: 100%;
  height: 120px;
  background: #ccc;
  text-align: center;
}

.centered-content {
  display: inline-block;
  background: #fff;
  padding: 20px;
  border: 1px solid #000;
}
<div class="container">
  <div class="centered-content">
    Center this!
  </div>
</div>

In my experience, the best way to center a box both vertically and horizontally, is to use an additional container and apply the following properties :

display: table;
display: table-cell;
vertical-align: middle;
text-align: center;
display: inline-block;
.outer-container {
  display: table;
  width: 100%;
  height: 120px;
  background: #ccc;
}

.inner-container {
  display: table-cell;
  vertical-align: middle;
  text-align: center;
}

.centered-content {
  display: inline-block;
  background: #fff;
  padding: 20px;
  border: 1px solid #000;
}
<div class="outer-container">
  <div class="inner-container">
    <div class="centered-content">
      Center this!
    </div>
  </div>
</div>

html - How to horizontally center a
in another
? - Stack Ov...

html css alignment
Rectangle 27 204

But what if the container is not the viewport (body)?

This question is asked in comment by Alex under the accepted answer.

That fact does not mean vw cannot be used to some extent to size for that container. Now to see any variation at all one has to be assuming that the container in some way is flexible in size. Whether through a direct percentage width or through being 100% minus margins. The point becomes "moot" if the container is always set to, let's say, 200px wide--then just set a font-size that works for that width.

With a flexible width container, however, it must be realized that in some way the container is still being sized off the view port. As such, it is a matter of adjusting a vw setting based off that percentage size difference to the view port, which means taking into account the sizing of parent wrappers. Take this example:

div {
    width: 50%;
    border: 1px solid black;
    margin: 20px;
    font-size: 16px;
    /* 100 = view port width, as 1vw = 1/100th of that
       So if the container is 50% of view port (as here)
       then factor that into how you want it to size.
       Let's say you like 5vw if it were the whole width,
       then for this container, size it at 2.5vw (5 * .5 [i.e. 50%])
    */
    font-size: 2.5vw; 
}

Assuming here the div is a child of the body, it is 50% of that 100% width, which is the viewport size in this basic case. Basically, you want to set a vw that is going to look good to you. As you can see in my comment in the above css, you can "think" through that mathematically with respect to the full viewport size, but you don't need to do that. The text is going to "flex" with the container, because the container is flexing with the viewport resizing. UPDATE: here's an example of two differently sized containers.

You can help insure viewport sizing by forcing the calculation based off that. Consider this example:

html {width: 100%;} /* force html to be viewport width */
body {width: 150%; } /* overflow the body */

div {
    width: 50%;
    border: 1px solid black;
    margin: 20px;
    font-size: 16px;
    /* 100 = view port width, as 1vw = 1/100th of that
       Here, the body is 200% of viewport, but the container is 50% 
       of view port, so both parents factor  into how you want it to size.
       Let's say you like 5vw if it were the whole width,
       then for this container, size it at 3.75vw 
       (5 * 1.5 [i.e. 150%]) * .5 [i.e. 50%]
    */
    font-size: 3.75vw; 
}

The sizing is still based off viewport, but is in essence set up based off the container size itself.

If sizing of the container element ended up changing dynamically its percentage relationship either via @media break points or via javascript, then whatever the base "target" was would need recalculation to maintain the same "relationship" for text sizing.

Take Example #1 above. If the div was switched to 25% width by either @media or javascript, then at the same time, the font-size would need to adjust in either the media query or by javascript to the new calculation of 5vw * .25 = 1.25. This would put the text size at the same size it would have been had the "width" of the original 50% container been reduced by half from viewport sizing, but has now been reduced due to a change in its own percentage calculation.

With the CSS3 calc() function in use, it would become difficult to adjust dynamically, as that function does not work for font-size purposes at this time. So you could not do a pure CSS3 adjustment if your width is changing on calc(). Of course, a minor adjustment of width for margins may not be enough to warrant any change in font-size, so it may not matter.

@thirtydot: That's unfortunate (but good to be aware of, thanks). Hope the bug gets resolved soon, but it looks like it has been persisting for some time.

Great answer, however, it won't work if the containing element has a max-width.

@KristofferNolgren: That relates to two points made in my answer: (1) "assuming that the container in some way is flexible in size" (once 'max-width' is reached, it no longer flexes, so there is then an issue). (2) If one can determine at what point 'max-width' would be reached, then as I noted, you could set an @media break point to change how the font is sized at that point (essentially giving it a fixed size at reaching max-width). Just a thought to work with a max-width situation.

Do you think you can throw up a fiddle of when the container element is changing dynamically through media queries? I'm not sure I understand.

css - Font scaling based on width of container - Stack Overflow

css responsive-design font-size
Rectangle 27 204

But what if the container is not the viewport (body)?

This question is asked in comment by Alex under the accepted answer.

That fact does not mean vw cannot be used to some extent to size for that container. Now to see any variation at all one has to be assuming that the container in some way is flexible in size. Whether through a direct percentage width or through being 100% minus margins. The point becomes "moot" if the container is always set to, let's say, 200px wide--then just set a font-size that works for that width.

With a flexible width container, however, it must be realized that in some way the container is still being sized off the view port. As such, it is a matter of adjusting a vw setting based off that percentage size difference to the view port, which means taking into account the sizing of parent wrappers. Take this example:

div {
    width: 50%;
    border: 1px solid black;
    margin: 20px;
    font-size: 16px;
    /* 100 = view port width, as 1vw = 1/100th of that
       So if the container is 50% of view port (as here)
       then factor that into how you want it to size.
       Let's say you like 5vw if it were the whole width,
       then for this container, size it at 2.5vw (5 * .5 [i.e. 50%])
    */
    font-size: 2.5vw; 
}

Assuming here the div is a child of the body, it is 50% of that 100% width, which is the viewport size in this basic case. Basically, you want to set a vw that is going to look good to you. As you can see in my comment in the above css, you can "think" through that mathematically with respect to the full viewport size, but you don't need to do that. The text is going to "flex" with the container, because the container is flexing with the viewport resizing. UPDATE: here's an example of two differently sized containers.

You can help insure viewport sizing by forcing the calculation based off that. Consider this example:

html {width: 100%;} /* force html to be viewport width */
body {width: 150%; } /* overflow the body */

div {
    width: 50%;
    border: 1px solid black;
    margin: 20px;
    font-size: 16px;
    /* 100 = view port width, as 1vw = 1/100th of that
       Here, the body is 200% of viewport, but the container is 50% 
       of view port, so both parents factor  into how you want it to size.
       Let's say you like 5vw if it were the whole width,
       then for this container, size it at 3.75vw 
       (5 * 1.5 [i.e. 150%]) * .5 [i.e. 50%]
    */
    font-size: 3.75vw; 
}

The sizing is still based off viewport, but is in essence set up based off the container size itself.

If sizing of the container element ended up changing dynamically its percentage relationship either via @media break points or via javascript, then whatever the base "target" was would need recalculation to maintain the same "relationship" for text sizing.

Take Example #1 above. If the div was switched to 25% width by either @media or javascript, then at the same time, the font-size would need to adjust in either the media query or by javascript to the new calculation of 5vw * .25 = 1.25. This would put the text size at the same size it would have been had the "width" of the original 50% container been reduced by half from viewport sizing, but has now been reduced due to a change in its own percentage calculation.

With the CSS3 calc() function in use, it would become difficult to adjust dynamically, as that function does not work for font-size purposes at this time. So you could not do a pure CSS3 adjustment if your width is changing on calc(). Of course, a minor adjustment of width for margins may not be enough to warrant any change in font-size, so it may not matter.

@thirtydot: That's unfortunate (but good to be aware of, thanks). Hope the bug gets resolved soon, but it looks like it has been persisting for some time.

Great answer, however, it won't work if the containing element has a max-width.

@KristofferNolgren: That relates to two points made in my answer: (1) "assuming that the container in some way is flexible in size" (once 'max-width' is reached, it no longer flexes, so there is then an issue). (2) If one can determine at what point 'max-width' would be reached, then as I noted, you could set an @media break point to change how the font is sized at that point (essentially giving it a fixed size at reaching max-width). Just a thought to work with a max-width situation.

Do you think you can throw up a fiddle of when the container element is changing dynamically through media queries? I'm not sure I understand.

css - Font scaling based on width of container - Stack Overflow

css responsive-design font-size
Rectangle 27 217

But what if the container is not the viewport (body)?

This question is asked in comment by Alex under the accepted answer.

That fact does not mean vw cannot be used to some extent to size for that container. Now to see any variation at all one has to be assuming that the container in some way is flexible in size. Whether through a direct percentage width or through being 100% minus margins. The point becomes "moot" if the container is always set to, let's say, 200px wide--then just set a font-size that works for that width.

With a flexible width container, however, it must be realized that in some way the container is still being sized off the view port. As such, it is a matter of adjusting a vw setting based off that percentage size difference to the view port, which means taking into account the sizing of parent wrappers. Take this example:

div {
    width: 50%;
    border: 1px solid black;
    margin: 20px;
    font-size: 16px;
    /* 100 = view port width, as 1vw = 1/100th of that
       So if the container is 50% of view port (as here)
       then factor that into how you want it to size.
       Let's say you like 5vw if it were the whole width,
       then for this container, size it at 2.5vw (5 * .5 [i.e. 50%])
    */
    font-size: 2.5vw; 
}

Assuming here the div is a child of the body, it is 50% of that 100% width, which is the viewport size in this basic case. Basically, you want to set a vw that is going to look good to you. As you can see in my comment in the above css, you can "think" through that mathematically with respect to the full viewport size, but you don't need to do that. The text is going to "flex" with the container, because the container is flexing with the viewport resizing. UPDATE: here's an example of two differently sized containers.

You can help insure viewport sizing by forcing the calculation based off that. Consider this example:

html {width: 100%;} /* force html to be viewport width */
body {width: 150%; } /* overflow the body */

div {
    width: 50%;
    border: 1px solid black;
    margin: 20px;
    font-size: 16px;
    /* 100 = view port width, as 1vw = 1/100th of that
       Here, the body is 200% of viewport, but the container is 50% 
       of view port, so both parents factor  into how you want it to size.
       Let's say you like 5vw if it were the whole width,
       then for this container, size it at 3.75vw 
       (5 * 1.5 [i.e. 150%]) * .5 [i.e. 50%]
    */
    font-size: 3.75vw; 
}

The sizing is still based off viewport, but is in essence set up based off the container size itself.

If sizing of the container element ended up changing dynamically its percentage relationship either via @media break points or via javascript, then whatever the base "target" was would need recalculation to maintain the same "relationship" for text sizing.

Take Example #1 above. If the div was switched to 25% width by either @media or javascript, then at the same time, the font-size would need to adjust in either the media query or by javascript to the new calculation of 5vw * .25 = 1.25. This would put the text size at the same size it would have been had the "width" of the original 50% container been reduced by half from viewport sizing, but has now been reduced due to a change in its own percentage calculation.

With the CSS3 calc() function in use, it would become difficult to adjust dynamically, as that function does not work for font-size purposes at this time. So you could not do a pure CSS3 adjustment if your width is changing on calc(). Of course, a minor adjustment of width for margins may not be enough to warrant any change in font-size, so it may not matter.

@thirtydot: That's unfortunate (but good to be aware of, thanks). Hope the bug gets resolved soon, but it looks like it has been persisting for some time.

Great answer, however, it won't work if the containing element has a max-width.

@KristofferNolgren: That relates to two points made in my answer: (1) "assuming that the container in some way is flexible in size" (once 'max-width' is reached, it no longer flexes, so there is then an issue). (2) If one can determine at what point 'max-width' would be reached, then as I noted, you could set an @media break point to change how the font is sized at that point (essentially giving it a fixed size at reaching max-width). Just a thought to work with a max-width situation.

Do you think you can throw up a fiddle of when the container element is changing dynamically through media queries? I'm not sure I understand.

css - Font scaling based on width of container - Stack Overflow

css responsive-design font-size
Rectangle 27 65

Using a Dependency Injection Container

  • Application needs Foo (e.g. a controller), so:
  • Foo needs Bar (e.g. a service), so:
  • Bar needs Bim (a service, a repository, ), so:
  • a DI Container is a tool to help injecting dependencies

You don't need a container to do dependency injection. However a container can help you.

design patterns - What is dependency injection? - Stack Overflow

design-patterns language-agnostic dependency-injection terminology
Rectangle 27 204

But what if the container is not the viewport (body)?

This question is asked in comment by Alex under the accepted answer.

That fact does not mean vw cannot be used to some extent to size for that container. Now to see any variation at all one has to be assuming that the container in some way is flexible in size. Whether through a direct percentage width or through being 100% minus margins. The point becomes "moot" if the container is always set to, let's say, 200px wide--then just set a font-size that works for that width.

With a flexible width container, however, it must be realized that in some way the container is still being sized off the view port. As such, it is a matter of adjusting a vw setting based off that percentage size difference to the view port, which means taking into account the sizing of parent wrappers. Take this example:

div {
    width: 50%;
    border: 1px solid black;
    margin: 20px;
    font-size: 16px;
    /* 100 = view port width, as 1vw = 1/100th of that
       So if the container is 50% of view port (as here)
       then factor that into how you want it to size.
       Let's say you like 5vw if it were the whole width,
       then for this container, size it at 2.5vw (5 * .5 [i.e. 50%])
    */
    font-size: 2.5vw; 
}

Assuming here the div is a child of the body, it is 50% of that 100% width, which is the viewport size in this basic case. Basically, you want to set a vw that is going to look good to you. As you can see in my comment in the above css, you can "think" through that mathematically with respect to the full viewport size, but you don't need to do that. The text is going to "flex" with the container, because the container is flexing with the viewport resizing. UPDATE: here's an example of two differently sized containers.

You can help insure viewport sizing by forcing the calculation based off that. Consider this example:

html {width: 100%;} /* force html to be viewport width */
body {width: 150%; } /* overflow the body */

div {
    width: 50%;
    border: 1px solid black;
    margin: 20px;
    font-size: 16px;
    /* 100 = view port width, as 1vw = 1/100th of that
       Here, the body is 200% of viewport, but the container is 50% 
       of view port, so both parents factor  into how you want it to size.
       Let's say you like 5vw if it were the whole width,
       then for this container, size it at 3.75vw 
       (5 * 1.5 [i.e. 150%]) * .5 [i.e. 50%]
    */
    font-size: 3.75vw; 
}

The sizing is still based off viewport, but is in essence set up based off the container size itself.

If sizing of the container element ended up changing dynamically its percentage relationship either via @media break points or via javascript, then whatever the base "target" was would need recalculation to maintain the same "relationship" for text sizing.

Take Example #1 above. If the div was switched to 25% width by either @media or javascript, then at the same time, the font-size would need to adjust in either the media query or by javascript to the new calculation of 5vw * .25 = 1.25. This would put the text size at the same size it would have been had the "width" of the original 50% container been reduced by half from viewport sizing, but has now been reduced due to a change in its own percentage calculation.

With the CSS3 calc() function in use, it would become difficult to adjust dynamically, as that function does not work for font-size purposes at this time. So you could not do a pure CSS3 adjustment if your width is changing on calc(). Of course, a minor adjustment of width for margins may not be enough to warrant any change in font-size, so it may not matter.

@thirtydot: That's unfortunate (but good to be aware of, thanks). Hope the bug gets resolved soon, but it looks like it has been persisting for some time.

Great answer, however, it won't work if the containing element has a max-width.

@KristofferNolgren: That relates to two points made in my answer: (1) "assuming that the container in some way is flexible in size" (once 'max-width' is reached, it no longer flexes, so there is then an issue). (2) If one can determine at what point 'max-width' would be reached, then as I noted, you could set an @media break point to change how the font is sized at that point (essentially giving it a fixed size at reaching max-width). Just a thought to work with a max-width situation.

Do you think you can throw up a fiddle of when the container element is changing dynamically through media queries? I'm not sure I understand.

css - Font scaling based on width of container - Stack Overflow

css responsive-design font-size
Rectangle 27 63

Using a Dependency Injection Container

  • Application needs Foo (e.g. a controller), so:
  • Foo needs Bar (e.g. a service), so:
  • Bar needs Bim (a service, a repository, ), so:
  • a DI Container is a tool to help injecting dependencies

You don't need a container to do dependency injection. However a container can help you.

design patterns - What is dependency injection? - Stack Overflow

design-patterns language-agnostic dependency-injection terminology
Rectangle 27 63

Using a Dependency Injection Container

  • Application needs Foo (e.g. a controller), so:
  • Foo needs Bar (e.g. a service), so:
  • Bar needs Bim (a service, a repository, ), so:
  • a DI Container is a tool to help injecting dependencies

You don't need a container to do dependency injection. However a container can help you.

design patterns - What is dependency injection? - Stack Overflow

design-patterns language-agnostic dependency-injection terminology
Rectangle 27 1026

:before and :after render inside a container

and <input> can not contain other elements.

Pseudo-elements can only be defined (or better said are only supported) on container elements. Because the way they are rendered is within the container itself as a child element. input can not contain other elements hence they're not supported. A button on the other hand that's also a form element supports them, because it's a container of other sub-elements.

If you ask me, if some browser does display these two pseudo-elements on non-container elements, it's a bug and a non-standard conformance. Specification directly talks about element content...

If we carefully read the specification it actually says that they are inserted inside a containing element:

Authors specify the style and location of generated content with the :before and :after pseudo-elements. As their names indicate, the :before and :after pseudo-elements specify the location of content before and after an element's document tree content. The 'content' property, in conjunction with these pseudo-elements, specifies what is inserted.

+1 Much better than the accepted answer. Thanks for the clear explanation of the standard itself. So much for [required]::before { content "*"; color: red; } :P

Tip: If you're having the problem with just a submit input like <input type="submit" value="Send"/>, use <button type="submit">Send</button> instead. The presentation is identical but the <button> is a container and thus supports :beforeand :after.

What about <hr />? I thought it wasn't a container element, but it could render :after and :before jsfiddle.net/Uf88j/1

@deathlock: that is indeed interesting. I would say it must be some kind of an anomaly and I wouldn't rely on it working cross browser or cross versions... HR is not a container element hence should not allow for pseudo elements. Even W3C standard says that it allows no content. And if you check for void element you can see that these elements shouldn't have any content under any circumstances. Pseudo elements are content so expect future browser version to fail to display them.

":before and :after render inside a container" The :before and :after pseudo elements come "before and after the content". Not "at the beginning or end of" the container. The spec does not mention a container. With tags like p and h1, the content is within the tag, so before/after appear inside as well. With elements like input and hr, :before and :after would still appear before or after the content, but there is no container involved (especially for input). input:checked:before is widely used to indicate checkboxes being checked via css.

html - Can I use a :before or :after pseudo-element on an input field?...

html css pseudo-element css-content