Related
I've been working on designs with very irregularly-shaped divs, such as rhombuses, trapezoids, etc. I want to know what the most responsive way to deal with these types of designs.
My current workaround:
The typical way I implement these designs is by using a combination of clip-path, bloated vertical padding to deal with the clip-path clipping content, and then a negative margin-top on the next fold to cover the white-space created by the clip-path. I declare negative margin-top values with viewport width (ex. -10vw), so the folds adjust based on the width of the browser.
Problems with current workaround:
Negative margins usually cause folds to overlap each other, covering the content of other folds. Multiple #media queries needed for it to look acceptable and yet I still encounter certain sizes where the folds overlap each other.
Here's an image to further describe what I mean by irregularly-shaped divs/folds:
https://imgur.com/a/jCbJZS4
Any help would be appreciated. These sort of designs seem to be trending, so your help will serve me and others for future projects as well. Thank you!
SVGs are a nice way to create section dividers as per your image,(and other complex shapes!) you can target the various shapes inside an svg with css (change fill colour, animations etc), they are widely supported (except for old IE browsers, naturally) and as they are simply vector paths, you can easily stretch, scale and distort, and they're quite small in size.
You might set an svg divider e.g. a wave pattern inside an absolutely positioned div at the bottom of a content section, like below.
section {
position: relative;
width: 100%;
margin: 0;
padding: 0;
}
#sect1 {
background-color: #2baf70;
}
#sect2 {
background-color: #f9f9f9;
}
.row {
max-width: 900px;
margin-left: auto;
margin-right: auto;
padding: 45px 45px 115px 45px;
}
.divider {
background-image: url(data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTAwJSIgaGVpZ2h0PSIxMDBweCIgdmlld0JveD0iMCAwIDEyODAgMTQwIiBwcmVzZXJ2ZUFzcGVjdFJhdGlvPSJub25lIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPjxnIGZpbGw9IiNmOWY5ZjkiPjxwYXRoIGQ9Ik0xMjgwIDMuNEMxMDUwLjU5IDE4IDEwMTkuNCA4NC44OSA3MzQuNDIgODQuODljLTMyMCAwLTMyMC04NC4zLTY0MC04NC4zQzU5LjQuNTkgMjguMiAxLjYgMCAzLjRWMTQwaDEyODB6IiBmaWxsLW9wYWNpdHk9Ii4zIi8+PHBhdGggZD0iTTAgMjQuMzFjNDMuNDYtNS42OSA5NC41Ni05LjI1IDE1OC40Mi05LjI1IDMyMCAwIDMyMCA4OS4yNCA2NDAgODkuMjQgMjU2LjEzIDAgMzA3LjI4LTU3LjE2IDQ4MS41OC04MFYxNDBIMHoiIGZpbGwtb3BhY2l0eT0iLjUiLz48cGF0aCBkPSJNMTI4MCA1MS43NmMtMjAxIDEyLjQ5LTI0Mi40MyA1My40LTUxMy41OCA1My40LTMyMCAwLTMyMC01Ny02NDAtNTctNDguODUuMDEtOTAuMjEgMS4zNS0xMjYuNDIgMy42VjE0MGgxMjgweiIvPjwvZz48L3N2Zz4=);
/* this is an inlined svg taken from a project I'm working on, as an example. as I can't really import a .svg file here */
width: 100%;
background-size: 100% 70px;
bottom: 0;
height: 70px;
z-index: 1;
display: block;
background-repeat-y: no-repeat;
position: absolute;
}
<section id="sect1">
<div class="row">
<h2>Mock Content</h2>
<p>Lorem ipsum dolor sit amet, affert omittam urbanitas est te. Eam ne oportere erroribus, quis veri eam cu, usu ex tota verear iudicabit. Vim modus conclusionemque an, verterem explicari sententiae ei duo. Mel cu docendi fierent, sonet dolorum ocurreret
at vis. Voluptua fabellas electram ut has, tation maluisset voluptatibus sea ex.</p>
</div>
<div class="divider"></div>
</section>
<section id="sect2">
<div class="row">
<h2>Mock Content</h2>
<p>Lorem ipsum dolor sit amet, affert omittam urbanitas est te. Eam ne oportere erroribus, quis veri eam cu, usu ex tota verear iudicabit. Vim modus conclusionemque an, verterem explicari sententiae ei duo. Mel cu docendi fierent, sonet dolorum ocurreret
at vis. Voluptua fabellas electram ut has, tation maluisset voluptatibus sea ex.</p>
</div>
</section>
I'm still relatively new to html and css, and I'm not able to figure this out. I have three divs with some text and I want them to be next to each other. I set them to float: left but they are not doing so.
.threethings {
width: 20%;
}
.threethings div {
text-align: center;
position: relative;
float: left;
}
<div class="threethings">
<div><span>Style</span>
<br>
<p>Lorem ipsum dolor sit amet, ius te ullum indoctum, sanctus consequat eum te. Nemore recteque necessitatibus et eos.</p>
</div>
<div><span>Style</span>
<br>
<p>Lorem ipsum dolor sit amet, ius te ullum indoctum, sanctus consequat eum te. Nemore recteque necessitatibus et eos.</p>
</div>
<div><span>Style</span>
<br>
<p>Lorem ipsum dolor sit amet, ius te ullum indoctum, sanctus consequat eum te. Nemore recteque necessitatibus et eos.</p>
</div>
</div>
try this
.threethings {
width : 100%;
}
.threethings div {
width: 20%;
text-align: center;
position: relative;
float : left;
}
so what happens is divs are floated in your case but not side by side as you are giving 20% width to parent , due which children cant fload side by side.
what i did was give parent some large width and children some small width, so that parent can accomodate children floating side by side.
well as div is block. width:100% might not be necessary
You're floating the parent class - not the divs containing paragraphs. Add the .threethings class to the 3 nested divs to instruct them to float their proceeding divs up alongside them.
Note that you may also need to give the divs a fixed width, as the paragraphs you have on there may exceed the length of your html body, which in turn would force them onto a new line.
Try this solution
.threethings {
width:100%;
}
.threethings div {
width:33%;
position: relative;
float : left;
}
This question already has answers here:
How to center an element horizontally and vertically
(27 answers)
Closed 4 years ago.
Best way to center a <div> element on a page both vertically and horizontally?
I know that margin-left: auto; margin-right: auto; will center on the horizontal, but what is the best way to do it vertically, too?
The best and most flexible way
The main trick in this demo is that in the normal flow of elements going from top to bottom, so the margin-top: auto is set to zero. However, an absolutely positioned element acts the same for distribution of free space, and similarly can be centered vertically at the specified top and bottom (does not work in IE7).
##This trick will work with any sizes of div.
div {
width: 100px;
height: 100px;
background-color: red;
position: absolute;
top:0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
}
<div></div>
Even though this did not work when the OP asked this question, I think, for modern browsers at least, the best solution is to use display: flex or pseudo classes.
You can see an example in the following fiddle.
Here is the updated fiddle.
For pseudo classes an example could be:
.centerPseudo {
display:inline-block;
text-align:center;
}
.centerPseudo::before{
content:'';
display:inline-block;
height:100%;
vertical-align:middle;
width:0px;
}
The usage of display: flex, according to css-tricks and MDN is as follows:
.centerFlex {
align-items: center;
display: flex;
justify-content: center;
}
There are other attributes available for flex, which are explained in above mentioned links, with further examples.
If you have to support older browsers, which don't support css3, then you should probably use javascript or the fixed width/height solution shown in the other answers.
Simplicity of this technique is stunning:
(This method has its implications though, but if you only need to center element regardless of flow of the rest of the content, it's just fine. Use with care)
Markup:
<div>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum accumsan tellus purus, et mollis nulla consectetur ac. Quisque id elit at diam convallis venenatis eget sed justo. Nunc egestas enim mauris, sit amet tempor risus ultricies in. Sed dignissim magna erat, vel laoreet tortor bibendum vitae. Ut porttitor tincidunt est imperdiet vestibulum. Vivamus id nibh tellus. Integer massa orci, gravida non imperdiet sed, consectetur ac quam. Nunc dignissim felis id tortor tincidunt, a eleifend nulla molestie. Phasellus eleifend leo purus, vel facilisis massa dignissim vitae. Pellentesque libero sapien, tincidunt ut lorem non, porta accumsan risus. Morbi tempus pharetra ex, vel luctus turpis tempus eu. Integer vitae sagittis massa, id gravida erat. Maecenas sed purus et magna tincidunt faucibus nec eget erat. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc nec mollis sem.</div>
And CSS:
div {
color: white;
background: red;
padding: 15px;
position: absolute;
top: 50%;
left: 50%;
-ms-transform: translateX(-50%) translateY(-50%);
-webkit-transform: translate(-50%,-50%);
transform: translate(-50%,-50%);
}
This will center element horizontally and vertically too. No negative margins, just power of transforms. Also we should already forget about IE8 shouldn't we?
I would use translate:
First position the div's top left corner at the center of the page (using position: fixed; top: 50%; left: 50%). Then, translate moves it up by 50% of the div's height to center it vertically on the page. Finally, translate also moves the div to the right by 50% of it's width to center it horizontally.
I actually think that this method is better than many of the others, since it does not require any changes on the parent element.
translate is better than translate3d in some scenarios due to it being supported by a greater number of browsers. https://caniuse.com/#feat=transforms2d
To sum it up, this method is supported on all versions of Chrome, Firefox 3.5+, Opera 11.5+, all versions of Safari, IE 9+, and Edge.
.centered {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
-webkit-transform: translate(-50%, -50%);
-moz-transform: translate(-50%, -50%);
-o-transform: translate(-50%, -50%);
-ms-transform: translate(-50%, -50%);
font-size: 20px;
background-color: cyan;
border: darkgreen 5px solid;
padding: 5px;
z-index: 100;
}
table {
position: absolute;
top: 0;
left: 0;
}
td {
position: relative;
top: 0;
left: 0;
}
<table>
<tr>
<td>
<div class="centered">This div<br />is centered</div>
<p>
Lorem ipsum dolor sit amet, nam sint laoreet at, his ne sumo causae, simul decore deterruisset ne mel. Exerci atomorum est ut. At choro vituperatoribus usu. Dico epicurei persequeris quo ex, ea ius zril phaedrum eloquentiam, duo in aperiam admodum fuisset. No quidam consequuntur usu, in amet hinc simul eos. Ex soleat meliore percipitur mea, nihil omittam salutandi ut eos. Mea et impedit facilisi pertinax, ea viris graeci fierent pri, te sonet intellegebat his. Vis denique albucius instructior ad, ex eum iudicabit elaboraret. Sit ea intellegam liberavisse. Nusquam quaestio maiestatis ut qui, eam decore altera te. Unum cibo aliquip ut qui, te mea doming prompta. Ex rebum interesset nam, te nam zril suscipit, qui suavitate explicari appellantur te. Usu brute corpora mandamus eu. Dicit soluta his eu. In sint consequat sed, quo ea tota petentium. Adhuc prompta splendide mel ad, soluta delenit nec cu.
</p>
</td>
<td>
<p>
Lorem ipsum dolor sit amet, dico choro recteque te cum, ex omnesque consectetuer sed, alii esse utinam et has. An qualisque democritum usu. Ea has habeo labores, laoreet intellegat te mea. Eius equidem inermis vel ne. Ne eum sonet labitur, nec id natum munere. Primis graecis est cu, quis dictas eu mea, eu quem offendit forensibus nec. Id animal mandamus his, vis in sonet tempor luptatum. Ne civibus oporteat comprehensam vix, per facete discere atomorum eu. Mucius probatus volutpat sit an, sumo nominavi democritum eam ut. Ea sit choro graece debitis, per ex verear voluptua epicurei. Id eum wisi dicat, ea sit velit doming cotidieque, eu sea amet delenit. Populo tacimates dissentiunt has cu. Has wisi hendrerit at, et quo doming putent docendi. Ea nibh vide omnium usu.
</p>
</td>
</tr>
</table>
Notice, however, that this method makes this div stay in one place while the page is being scrolled. This may be what you want but if not, there is another method.
Now, if we try the same CSS, but with position set to absolute, it will be in the center of the last parent that has an absolute position.
.centered {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
-webkit-transform: translate(-50%, -50%);
-moz-transform: translate(-50%, -50%);
-o-transform: translate(-50%, -50%);
-ms-transform: translate(-50%, -50%);
font-size: 20px;
background-color: cyan;
border: darkgreen 5px solid;
padding: 5px;
z-index: 100;
}
table {
position: absolute;
top: 0;
left: 0;
}
td {
position: relative;
top: 0;
left: 0;
}
<table>
<tr>
<td>
<div class="centered">This div<br />is centered</div>
<p>
Lorem ipsum dolor sit amet, nam sint laoreet at, his ne sumo causae, simul decore deterruisset ne mel. Exerci atomorum est ut. At choro vituperatoribus usu. Dico epicurei persequeris quo ex, ea ius zril phaedrum eloquentiam, duo in aperiam admodum fuisset. No quidam consequuntur usu, in amet hinc simul eos. Ex soleat meliore percipitur mea, nihil omittam salutandi ut eos. Mea et impedit facilisi pertinax, ea viris graeci fierent pri, te sonet intellegebat his. Vis denique albucius instructior ad, ex eum iudicabit elaboraret. Sit ea intellegam liberavisse. Nusquam quaestio maiestatis ut qui, eam decore altera te. Unum cibo aliquip ut qui, te mea doming prompta. Ex rebum interesset nam, te nam zril suscipit, qui suavitate explicari appellantur te. Usu brute corpora mandamus eu. Dicit soluta his eu. In sint consequat sed, quo ea tota petentium. Adhuc prompta splendide mel ad, soluta delenit nec cu.
</p>
</td>
<td>
<p>
Lorem ipsum dolor sit amet, dico choro recteque te cum, ex omnesque consectetuer sed, alii esse utinam et has. An qualisque democritum usu. Ea has habeo labores, laoreet intellegat te mea. Eius equidem inermis vel ne. Ne eum sonet labitur, nec id natum munere. Primis graecis est cu, quis dictas eu mea, eu quem offendit forensibus nec. Id animal mandamus his, vis in sonet tempor luptatum. Ne civibus oporteat comprehensam vix, per facete discere atomorum eu. Mucius probatus volutpat sit an, sumo nominavi democritum eam ut. Ea sit choro graece debitis, per ex verear voluptua epicurei. Id eum wisi dicat, ea sit velit doming cotidieque, eu sea amet delenit. Populo tacimates dissentiunt has cu. Has wisi hendrerit at, et quo doming putent docendi. Ea nibh vide omnium usu.
</p>
</td>
</tr>
</table>
Simple solution taking advantage of Flex Display
<div style = 'display:flex; position:absolute; top:0; bottom:0; right:0; left:0; '>
<div id = 'div_you_want_centered' style = 'margin:auto;'>
This will be Centered
</div>
</div>
Check out http://css-tricks.com/snippets/css/a-guide-to-flexbox/
The first div takes up the whole screen and has a display:flex set for every browser. The second div (centered div) takes advantage of the display:flex div where margin:auto works brilliantly.
Note IE11+ compatibility. (IE10 w/ prefix).
Using Flex-box in my opinion:
#parent {
display: flex;
justify-content: center;
align-items: center;
}
<div id="parent">
<div id="child">Hello World!</div>
</div>
You see there are only three CSS properties that you have to use to center the child element vertically and horizontally. display: flex; Do the main part by just activating Flex-box display, justify-content: center; center the child element vertically and align-items: center; center it horizontally. To see the best result I just add some extra styles :
#parent {
display: flex;
justify-content: center;
align-items: center;
height: 500px;
width: 500px;
background: yellow;
}
#child {
width: 100px;
height: 100px;
background: silver;
}
<div id="parent">
<div id="child">Hello World!</div>
</div>
If you want to learn more about Flex-box you can visit W3Schools, MDN or CSS-Tricks for more information.
I think there are two ways to make a div center align through CSS.
.middleDiv {
position : absolute;
width : 200px;
height : 200px;
left : 50%;
top : 50%;
margin-left : -100px; /* half of the width */
margin-top : -100px; /* half of the height */
}
This is the simple and best way. for the demo please visit below link:
http://w3webpro.blogspot.in/2013/07/how-to-make-div-horizontally-and.html
If you are looking at the new browsers(IE10+),
then you can make use of transform property to align a div at the center.
<div class="center-block">this is any div</div>
And css for this should be:
.center-block {
top:50%;
left: 50%;
transform: translate3d(-50%,-50%, 0);
position: absolute;
}
The catch here is that you don't even have to specify the height and width of the div as it takes care by itself.
Also, if you want to position a div at the center of another div, then you can just specify the position of outer div as relative and then this CSS starts working for your div.
How it works:
When you specify left and top at 50%, the div goes at the the bottom right quarter of the page with its top-left end pinned at the center of the page.
This is because, the left/top properties(when given in %) are calculated based on height of the outer div(in your case, window).
But transform uses height/width of the element to determine translation, so you div will move left(50% width) and top(50% its height) since they are given in negatives, thus aligning it to the center of the page.
If you have to support older browsers(and sorry including IE9 as well) then the table cell is most popular method to use.
My prefered way to center a box both vertically and horizontally, is the following technique :
The outer container
should have display: table;
The inner container
should have display: table-cell;
should have vertical-align: middle;
should have text-align: center;
The content box
should have display: inline-block;
should re-adjust the horizontal text-alignment to eg. text-align: left; or text-align: right;, unless you want text to be centered
The elegance of this technique, is that you can add your content to the content box without worrying about its height or width!
Demo
body {
margin : 0;
}
.outer-container {
position : absolute;
display: table;
width: 100%; /* This could be ANY width */
height: 100%; /* This could be ANY height */
background: #ccc;
}
.inner-container {
display: table-cell;
vertical-align: middle;
text-align: center;
}
.centered-content {
display: inline-block;
text-align: left;
background: #fff;
padding : 20px;
border : 1px solid #000;
}
<div class="outer-container">
<div class="inner-container">
<div class="centered-content">
You can put anything here!
</div>
</div>
</div>
See also this Fiddle!
EDIT
Yes, I know you can achieve more or less the same flexibility with transform: translate(-50%, -50%); or transform: translate3d(-50%,-50%, 0);, the technique I'm proposing has far better browser support. Even with browsers prefixes like -webkit, -ms or -moz, transform doesn't offer quite the same browser support.
So if you care about older browsers (eg. IE9 and below), you should not use transform for positioning.
position: absolute;
left: 50%;
top: 50%;
-webkit-transform: translate(-50%, -50%);
-ms-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
Explanation:
Give it an absolute positioning (the parent should have relative positioning). Then, the upper left corner is moved to the center. Because you don't know the width/height yet, you use css transform to translate the position relatively to the middle. translate(-50%, -50%) does reduce the x and y position of the upper left corner by 50% of width and height.
Here is a script i wrote a while back (it is written using the jQuery library):
var centerIt = function (el /* (jQuery element) Element to center */) {
if (!el) {
return;
}
var moveIt = function () {
var winWidth = $(window).width();
var winHeight = $(window).height();
el.css("position","absolute").css("left", ((winWidth / 2) - (el.width() / 2)) + "px").css("top", ((winHeight / 2) - (el.height() / 2)) + "px");
};
$(window).resize(moveIt);
moveIt();
};
This is the best code to centre the div bot horizontally and vertically
div
{
position:absolute;
top:50%;
left:50%;
transform:translate(-50%,-50%);
}
I know I am late to the party but here is a way to center a div with unknown dimension inside a parent of unknown dimension.
style:
<style>
.table {
display: table;
height: 100%;
margin: 0 auto;
}
.table-cell {
display: table-cell;
vertical-align: middle;
}
.centered {
background-color: red;
}
</style>
HTML:
<div class="table">
<div class="table-cell"><div class="centered">centered</div></div>
</div>
DEMO:
Check out this demo.
2018 way using CSS Grid:
.parent{
display: grid;
place-items: center center;
}
Check for browser support, Caniuse suggests it works from Chrome 57, FF 52, Opera 44, Safari 10.1, Edge 16. I didn't check myself.
See snippet below:
.parent{
display: grid;
place-items: center center;
/*place-items is a shorthand for align-items and justify-items*/
height: 200px;
border: 1px solid black;
background: gainsboro;
}
.child{
background: white;
}
<div class="parent">
<div class="child">Centered!</div>
</div>
Though I'm too late, but this is very easy and simple. Page center is always left 50%, and top 50%. So minus the div width and height 50% and set left margin and right margin. Hope it work's for everywhere -
body{
background: #EEE;
}
.center-div{
position: absolute;
width: 200px;
height: 60px;
left: 50%;
margin-left: -100px;
top: 50%;
margin-top: -30px;
background: #CCC;
color: #000;
text-align: center;
}
<div class="center-div">
<h3>This is center div</h3>
</div>
div {
border-style: solid;
position: fixed;
width: 80%;
height: 80%;
left: 10%;
top: 10%;
}
Adjust left and top with respect to width and height, that is (100% - 80%) / 2 = 10%
There is actually a solution, using css3, which can vertically center a div of unknown height. The trick is to move the div down by 50%, then use transformY to get it back up to the middle. The only prerequisite is that the to-be-centered element has a parent. Example:
<div class="parent">
<div class="center-me">
Text, images, whatever suits you.
</div>
</div>
.parent {
/* height can be whatever you want, also auto if you want a child
div to be responsible for the sizing */
height: 200px;
}
.center-me {
position: relative;
top: 50%;
transform: translateY(-50%);
/* prefixes needed for cross-browser support */
-ms-transform: translateY(-50%);
-webkit-transform: translateY(-50%);
}
Supported by all major browsers, and IE 9 and up (don't bother about IE 8, as it died together with win xp this autumn. Thank god.)
JS Fiddle Demo
Solution
Using only two lines of CSS, utilizing the magical power of Flexbox
.parent { display: flex; }
.child { margin: auto }
One more method (bulletproof) taken from here utilizing 'display:table' rule:
Markup
<div class="container">
<div class="outer">
<div class="inner">
<div class="centered">
...
</div>
</div>
</div>
</div>
CSS:
.outer {
display: table;
width: 100%;
height: 100%;
}
.inner {
display: table-cell;
vertical-align: middle;
text-align: center;
}
.centered {
position: relative;
display: inline-block;
width: 50%;
padding: 1em;
background: orange;
color: white;
}
I was looking at Laravel's view file and noticed that they centered text perfectly in the middle. I remembered about this question immediately.
This is how they did it:
<html>
<head>
<title>Laravel</title>
<!--<link href='//fonts.googleapis.com/css?family=Lato:100' rel='stylesheet' type='text/css'>-->
<style>
.container {
margin: 0;
padding: 0;
width: 100%;
height: 100%;
display: table;
}
.inside {
text-align: center;
display: table-cell;
vertical-align: middle;
}
</style>
</head>
<body>
<div class="container">
<div class="inside">This text is centered</div>
</div>
</body>
Result looks so:
An alternative answer would be this.
<div id="container">
<div id="centered"> </div>
</div>
and the css:
#container {
height: 400px;
width: 400px;
background-color: lightblue;
text-align: center;
}
#container:before {
height: 100%;
content: '';
display: inline-block;
vertical-align: middle;
}
#centered {
width: 100px;
height: 100px;
background-color: blue;
display: inline-block;
vertical-align: middle;
margin: 0 auto;
}
I'm surprised this has not been mentioned yet, but the simplest way to do this would be by setting the height, margin (and width, if you want) using viewport sizes.
As you might know, total height of the viewport = 100vh.
Say you want the height of you container to occupy 60% (60vh) of the screen, you can divide the rest (40vh) equally between the top and the bottom margin so that the element aligns itself in the centre automatically.
Setting the margin-left and margin-right to auto, will make sure the container is centred horizontally.
.container {
width: 60vw; /*optional*/
height: 60vh;
margin: 20vh auto;
background: #333;
}
<div class="container">
</div>
In case you know a defined sized for your div you could use calc.
Live example: https://jsfiddle.net/o8416eq3/
Notes: This works only if you hard coded the width and height of your ``div` in the CSS.
#target {
position:fixed;
top: calc(50vh - 100px/2);
left: calc(50vw - 200px/2);
width:200px;
height:100px;
background-color:red;
}
<div id='target'></div>
Using display:grid on parent and setting margin:auto to the centrerd elemnt will do the trick :
See below snippet :
html,body {
width :100%;
height:100%;
margin:0;
padding:0;
}
.container {
display:grid;
height:90%;
background-color:blue;
}
.content {
margin:auto;
color:white;
}
<div class="container">
<div class="content"> cented div here</div>
</div>
div {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
-ms-transform: translate(-50%, -50%); /* IE 9 */
-webkit-transform: translate(-50%, -50%); /* Chrome, Safari, Opera */
}
<body>
<div>Div to be aligned vertically</div>
</body>
position: absolute div in body document
An element with position: absolute; is positioned relative to the nearest positioned ancestor (instead of positioned relative to the viewport (body tag), like fixed).
However; if an absolute positioned element has no positioned ancestors, it uses the document body, and moves along with page scrolling.
source: CSS position
If you guys are using JQuery, you can do this by using .position();
<div class="positionthis"></div>
CSS
.positionthis {
width:100px;
height:100px;
position: absolute;
background:blue;
}
Javascript (JQuery)
$(document).ready(function () {
$('.positionthis').position({
of: $(document),
my: 'center center',
at: 'center center',
collision: 'flip flip'
});
});
JSFiddle : http://jsfiddle.net/vx9gV/
Is the browser supports it, using translate is powerful.
position: absolute;
background-color: red;
width: 70%;
height: 30%;
/* The translate % is relative to the size of the div and not the container*/
/* 21.42% = ( (100%-70%/2) / 0.7 ) */
/* 116.666% = ( (100%-30%/2) / 0.3 ) */
transform: translate3d( 21.42%, 116.666%, 0);
Sorry for late reply
best way is
div {
position: fixed;
top: 50%;
left: 50%;
margin-top: -50px;
margin-left: -100px;
}
margin-top and margin-left should be according to your div box size
Please use following CSS properties for center align element horizontally as well as vertically. This is worked fine for me.
div {
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0px;
margin: auto;
width: 100px;
height: 100px;
}
This solution worked for me
.middleDiv{
position : absolute;
height : 90%;
bottom: 5%;
}
(or height : 70% / bottom : 15%
height : 40% / bottom :30% ...)
This question already has answers here:
How to center an element horizontally and vertically
(27 answers)
Closed 4 years ago.
Best way to center a <div> element on a page both vertically and horizontally?
I know that margin-left: auto; margin-right: auto; will center on the horizontal, but what is the best way to do it vertically, too?
The best and most flexible way
The main trick in this demo is that in the normal flow of elements going from top to bottom, so the margin-top: auto is set to zero. However, an absolutely positioned element acts the same for distribution of free space, and similarly can be centered vertically at the specified top and bottom (does not work in IE7).
##This trick will work with any sizes of div.
div {
width: 100px;
height: 100px;
background-color: red;
position: absolute;
top:0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
}
<div></div>
Even though this did not work when the OP asked this question, I think, for modern browsers at least, the best solution is to use display: flex or pseudo classes.
You can see an example in the following fiddle.
Here is the updated fiddle.
For pseudo classes an example could be:
.centerPseudo {
display:inline-block;
text-align:center;
}
.centerPseudo::before{
content:'';
display:inline-block;
height:100%;
vertical-align:middle;
width:0px;
}
The usage of display: flex, according to css-tricks and MDN is as follows:
.centerFlex {
align-items: center;
display: flex;
justify-content: center;
}
There are other attributes available for flex, which are explained in above mentioned links, with further examples.
If you have to support older browsers, which don't support css3, then you should probably use javascript or the fixed width/height solution shown in the other answers.
Simplicity of this technique is stunning:
(This method has its implications though, but if you only need to center element regardless of flow of the rest of the content, it's just fine. Use with care)
Markup:
<div>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum accumsan tellus purus, et mollis nulla consectetur ac. Quisque id elit at diam convallis venenatis eget sed justo. Nunc egestas enim mauris, sit amet tempor risus ultricies in. Sed dignissim magna erat, vel laoreet tortor bibendum vitae. Ut porttitor tincidunt est imperdiet vestibulum. Vivamus id nibh tellus. Integer massa orci, gravida non imperdiet sed, consectetur ac quam. Nunc dignissim felis id tortor tincidunt, a eleifend nulla molestie. Phasellus eleifend leo purus, vel facilisis massa dignissim vitae. Pellentesque libero sapien, tincidunt ut lorem non, porta accumsan risus. Morbi tempus pharetra ex, vel luctus turpis tempus eu. Integer vitae sagittis massa, id gravida erat. Maecenas sed purus et magna tincidunt faucibus nec eget erat. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc nec mollis sem.</div>
And CSS:
div {
color: white;
background: red;
padding: 15px;
position: absolute;
top: 50%;
left: 50%;
-ms-transform: translateX(-50%) translateY(-50%);
-webkit-transform: translate(-50%,-50%);
transform: translate(-50%,-50%);
}
This will center element horizontally and vertically too. No negative margins, just power of transforms. Also we should already forget about IE8 shouldn't we?
I would use translate:
First position the div's top left corner at the center of the page (using position: fixed; top: 50%; left: 50%). Then, translate moves it up by 50% of the div's height to center it vertically on the page. Finally, translate also moves the div to the right by 50% of it's width to center it horizontally.
I actually think that this method is better than many of the others, since it does not require any changes on the parent element.
translate is better than translate3d in some scenarios due to it being supported by a greater number of browsers. https://caniuse.com/#feat=transforms2d
To sum it up, this method is supported on all versions of Chrome, Firefox 3.5+, Opera 11.5+, all versions of Safari, IE 9+, and Edge.
.centered {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
-webkit-transform: translate(-50%, -50%);
-moz-transform: translate(-50%, -50%);
-o-transform: translate(-50%, -50%);
-ms-transform: translate(-50%, -50%);
font-size: 20px;
background-color: cyan;
border: darkgreen 5px solid;
padding: 5px;
z-index: 100;
}
table {
position: absolute;
top: 0;
left: 0;
}
td {
position: relative;
top: 0;
left: 0;
}
<table>
<tr>
<td>
<div class="centered">This div<br />is centered</div>
<p>
Lorem ipsum dolor sit amet, nam sint laoreet at, his ne sumo causae, simul decore deterruisset ne mel. Exerci atomorum est ut. At choro vituperatoribus usu. Dico epicurei persequeris quo ex, ea ius zril phaedrum eloquentiam, duo in aperiam admodum fuisset. No quidam consequuntur usu, in amet hinc simul eos. Ex soleat meliore percipitur mea, nihil omittam salutandi ut eos. Mea et impedit facilisi pertinax, ea viris graeci fierent pri, te sonet intellegebat his. Vis denique albucius instructior ad, ex eum iudicabit elaboraret. Sit ea intellegam liberavisse. Nusquam quaestio maiestatis ut qui, eam decore altera te. Unum cibo aliquip ut qui, te mea doming prompta. Ex rebum interesset nam, te nam zril suscipit, qui suavitate explicari appellantur te. Usu brute corpora mandamus eu. Dicit soluta his eu. In sint consequat sed, quo ea tota petentium. Adhuc prompta splendide mel ad, soluta delenit nec cu.
</p>
</td>
<td>
<p>
Lorem ipsum dolor sit amet, dico choro recteque te cum, ex omnesque consectetuer sed, alii esse utinam et has. An qualisque democritum usu. Ea has habeo labores, laoreet intellegat te mea. Eius equidem inermis vel ne. Ne eum sonet labitur, nec id natum munere. Primis graecis est cu, quis dictas eu mea, eu quem offendit forensibus nec. Id animal mandamus his, vis in sonet tempor luptatum. Ne civibus oporteat comprehensam vix, per facete discere atomorum eu. Mucius probatus volutpat sit an, sumo nominavi democritum eam ut. Ea sit choro graece debitis, per ex verear voluptua epicurei. Id eum wisi dicat, ea sit velit doming cotidieque, eu sea amet delenit. Populo tacimates dissentiunt has cu. Has wisi hendrerit at, et quo doming putent docendi. Ea nibh vide omnium usu.
</p>
</td>
</tr>
</table>
Notice, however, that this method makes this div stay in one place while the page is being scrolled. This may be what you want but if not, there is another method.
Now, if we try the same CSS, but with position set to absolute, it will be in the center of the last parent that has an absolute position.
.centered {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
-webkit-transform: translate(-50%, -50%);
-moz-transform: translate(-50%, -50%);
-o-transform: translate(-50%, -50%);
-ms-transform: translate(-50%, -50%);
font-size: 20px;
background-color: cyan;
border: darkgreen 5px solid;
padding: 5px;
z-index: 100;
}
table {
position: absolute;
top: 0;
left: 0;
}
td {
position: relative;
top: 0;
left: 0;
}
<table>
<tr>
<td>
<div class="centered">This div<br />is centered</div>
<p>
Lorem ipsum dolor sit amet, nam sint laoreet at, his ne sumo causae, simul decore deterruisset ne mel. Exerci atomorum est ut. At choro vituperatoribus usu. Dico epicurei persequeris quo ex, ea ius zril phaedrum eloquentiam, duo in aperiam admodum fuisset. No quidam consequuntur usu, in amet hinc simul eos. Ex soleat meliore percipitur mea, nihil omittam salutandi ut eos. Mea et impedit facilisi pertinax, ea viris graeci fierent pri, te sonet intellegebat his. Vis denique albucius instructior ad, ex eum iudicabit elaboraret. Sit ea intellegam liberavisse. Nusquam quaestio maiestatis ut qui, eam decore altera te. Unum cibo aliquip ut qui, te mea doming prompta. Ex rebum interesset nam, te nam zril suscipit, qui suavitate explicari appellantur te. Usu brute corpora mandamus eu. Dicit soluta his eu. In sint consequat sed, quo ea tota petentium. Adhuc prompta splendide mel ad, soluta delenit nec cu.
</p>
</td>
<td>
<p>
Lorem ipsum dolor sit amet, dico choro recteque te cum, ex omnesque consectetuer sed, alii esse utinam et has. An qualisque democritum usu. Ea has habeo labores, laoreet intellegat te mea. Eius equidem inermis vel ne. Ne eum sonet labitur, nec id natum munere. Primis graecis est cu, quis dictas eu mea, eu quem offendit forensibus nec. Id animal mandamus his, vis in sonet tempor luptatum. Ne civibus oporteat comprehensam vix, per facete discere atomorum eu. Mucius probatus volutpat sit an, sumo nominavi democritum eam ut. Ea sit choro graece debitis, per ex verear voluptua epicurei. Id eum wisi dicat, ea sit velit doming cotidieque, eu sea amet delenit. Populo tacimates dissentiunt has cu. Has wisi hendrerit at, et quo doming putent docendi. Ea nibh vide omnium usu.
</p>
</td>
</tr>
</table>
Simple solution taking advantage of Flex Display
<div style = 'display:flex; position:absolute; top:0; bottom:0; right:0; left:0; '>
<div id = 'div_you_want_centered' style = 'margin:auto;'>
This will be Centered
</div>
</div>
Check out http://css-tricks.com/snippets/css/a-guide-to-flexbox/
The first div takes up the whole screen and has a display:flex set for every browser. The second div (centered div) takes advantage of the display:flex div where margin:auto works brilliantly.
Note IE11+ compatibility. (IE10 w/ prefix).
Using Flex-box in my opinion:
#parent {
display: flex;
justify-content: center;
align-items: center;
}
<div id="parent">
<div id="child">Hello World!</div>
</div>
You see there are only three CSS properties that you have to use to center the child element vertically and horizontally. display: flex; Do the main part by just activating Flex-box display, justify-content: center; center the child element vertically and align-items: center; center it horizontally. To see the best result I just add some extra styles :
#parent {
display: flex;
justify-content: center;
align-items: center;
height: 500px;
width: 500px;
background: yellow;
}
#child {
width: 100px;
height: 100px;
background: silver;
}
<div id="parent">
<div id="child">Hello World!</div>
</div>
If you want to learn more about Flex-box you can visit W3Schools, MDN or CSS-Tricks for more information.
I think there are two ways to make a div center align through CSS.
.middleDiv {
position : absolute;
width : 200px;
height : 200px;
left : 50%;
top : 50%;
margin-left : -100px; /* half of the width */
margin-top : -100px; /* half of the height */
}
This is the simple and best way. for the demo please visit below link:
http://w3webpro.blogspot.in/2013/07/how-to-make-div-horizontally-and.html
If you are looking at the new browsers(IE10+),
then you can make use of transform property to align a div at the center.
<div class="center-block">this is any div</div>
And css for this should be:
.center-block {
top:50%;
left: 50%;
transform: translate3d(-50%,-50%, 0);
position: absolute;
}
The catch here is that you don't even have to specify the height and width of the div as it takes care by itself.
Also, if you want to position a div at the center of another div, then you can just specify the position of outer div as relative and then this CSS starts working for your div.
How it works:
When you specify left and top at 50%, the div goes at the the bottom right quarter of the page with its top-left end pinned at the center of the page.
This is because, the left/top properties(when given in %) are calculated based on height of the outer div(in your case, window).
But transform uses height/width of the element to determine translation, so you div will move left(50% width) and top(50% its height) since they are given in negatives, thus aligning it to the center of the page.
If you have to support older browsers(and sorry including IE9 as well) then the table cell is most popular method to use.
My prefered way to center a box both vertically and horizontally, is the following technique :
The outer container
should have display: table;
The inner container
should have display: table-cell;
should have vertical-align: middle;
should have text-align: center;
The content box
should have display: inline-block;
should re-adjust the horizontal text-alignment to eg. text-align: left; or text-align: right;, unless you want text to be centered
The elegance of this technique, is that you can add your content to the content box without worrying about its height or width!
Demo
body {
margin : 0;
}
.outer-container {
position : absolute;
display: table;
width: 100%; /* This could be ANY width */
height: 100%; /* This could be ANY height */
background: #ccc;
}
.inner-container {
display: table-cell;
vertical-align: middle;
text-align: center;
}
.centered-content {
display: inline-block;
text-align: left;
background: #fff;
padding : 20px;
border : 1px solid #000;
}
<div class="outer-container">
<div class="inner-container">
<div class="centered-content">
You can put anything here!
</div>
</div>
</div>
See also this Fiddle!
EDIT
Yes, I know you can achieve more or less the same flexibility with transform: translate(-50%, -50%); or transform: translate3d(-50%,-50%, 0);, the technique I'm proposing has far better browser support. Even with browsers prefixes like -webkit, -ms or -moz, transform doesn't offer quite the same browser support.
So if you care about older browsers (eg. IE9 and below), you should not use transform for positioning.
position: absolute;
left: 50%;
top: 50%;
-webkit-transform: translate(-50%, -50%);
-ms-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
Explanation:
Give it an absolute positioning (the parent should have relative positioning). Then, the upper left corner is moved to the center. Because you don't know the width/height yet, you use css transform to translate the position relatively to the middle. translate(-50%, -50%) does reduce the x and y position of the upper left corner by 50% of width and height.
Here is a script i wrote a while back (it is written using the jQuery library):
var centerIt = function (el /* (jQuery element) Element to center */) {
if (!el) {
return;
}
var moveIt = function () {
var winWidth = $(window).width();
var winHeight = $(window).height();
el.css("position","absolute").css("left", ((winWidth / 2) - (el.width() / 2)) + "px").css("top", ((winHeight / 2) - (el.height() / 2)) + "px");
};
$(window).resize(moveIt);
moveIt();
};
This is the best code to centre the div bot horizontally and vertically
div
{
position:absolute;
top:50%;
left:50%;
transform:translate(-50%,-50%);
}
I know I am late to the party but here is a way to center a div with unknown dimension inside a parent of unknown dimension.
style:
<style>
.table {
display: table;
height: 100%;
margin: 0 auto;
}
.table-cell {
display: table-cell;
vertical-align: middle;
}
.centered {
background-color: red;
}
</style>
HTML:
<div class="table">
<div class="table-cell"><div class="centered">centered</div></div>
</div>
DEMO:
Check out this demo.
2018 way using CSS Grid:
.parent{
display: grid;
place-items: center center;
}
Check for browser support, Caniuse suggests it works from Chrome 57, FF 52, Opera 44, Safari 10.1, Edge 16. I didn't check myself.
See snippet below:
.parent{
display: grid;
place-items: center center;
/*place-items is a shorthand for align-items and justify-items*/
height: 200px;
border: 1px solid black;
background: gainsboro;
}
.child{
background: white;
}
<div class="parent">
<div class="child">Centered!</div>
</div>
Though I'm too late, but this is very easy and simple. Page center is always left 50%, and top 50%. So minus the div width and height 50% and set left margin and right margin. Hope it work's for everywhere -
body{
background: #EEE;
}
.center-div{
position: absolute;
width: 200px;
height: 60px;
left: 50%;
margin-left: -100px;
top: 50%;
margin-top: -30px;
background: #CCC;
color: #000;
text-align: center;
}
<div class="center-div">
<h3>This is center div</h3>
</div>
div {
border-style: solid;
position: fixed;
width: 80%;
height: 80%;
left: 10%;
top: 10%;
}
Adjust left and top with respect to width and height, that is (100% - 80%) / 2 = 10%
There is actually a solution, using css3, which can vertically center a div of unknown height. The trick is to move the div down by 50%, then use transformY to get it back up to the middle. The only prerequisite is that the to-be-centered element has a parent. Example:
<div class="parent">
<div class="center-me">
Text, images, whatever suits you.
</div>
</div>
.parent {
/* height can be whatever you want, also auto if you want a child
div to be responsible for the sizing */
height: 200px;
}
.center-me {
position: relative;
top: 50%;
transform: translateY(-50%);
/* prefixes needed for cross-browser support */
-ms-transform: translateY(-50%);
-webkit-transform: translateY(-50%);
}
Supported by all major browsers, and IE 9 and up (don't bother about IE 8, as it died together with win xp this autumn. Thank god.)
JS Fiddle Demo
Solution
Using only two lines of CSS, utilizing the magical power of Flexbox
.parent { display: flex; }
.child { margin: auto }
One more method (bulletproof) taken from here utilizing 'display:table' rule:
Markup
<div class="container">
<div class="outer">
<div class="inner">
<div class="centered">
...
</div>
</div>
</div>
</div>
CSS:
.outer {
display: table;
width: 100%;
height: 100%;
}
.inner {
display: table-cell;
vertical-align: middle;
text-align: center;
}
.centered {
position: relative;
display: inline-block;
width: 50%;
padding: 1em;
background: orange;
color: white;
}
I was looking at Laravel's view file and noticed that they centered text perfectly in the middle. I remembered about this question immediately.
This is how they did it:
<html>
<head>
<title>Laravel</title>
<!--<link href='//fonts.googleapis.com/css?family=Lato:100' rel='stylesheet' type='text/css'>-->
<style>
.container {
margin: 0;
padding: 0;
width: 100%;
height: 100%;
display: table;
}
.inside {
text-align: center;
display: table-cell;
vertical-align: middle;
}
</style>
</head>
<body>
<div class="container">
<div class="inside">This text is centered</div>
</div>
</body>
Result looks so:
An alternative answer would be this.
<div id="container">
<div id="centered"> </div>
</div>
and the css:
#container {
height: 400px;
width: 400px;
background-color: lightblue;
text-align: center;
}
#container:before {
height: 100%;
content: '';
display: inline-block;
vertical-align: middle;
}
#centered {
width: 100px;
height: 100px;
background-color: blue;
display: inline-block;
vertical-align: middle;
margin: 0 auto;
}
I'm surprised this has not been mentioned yet, but the simplest way to do this would be by setting the height, margin (and width, if you want) using viewport sizes.
As you might know, total height of the viewport = 100vh.
Say you want the height of you container to occupy 60% (60vh) of the screen, you can divide the rest (40vh) equally between the top and the bottom margin so that the element aligns itself in the centre automatically.
Setting the margin-left and margin-right to auto, will make sure the container is centred horizontally.
.container {
width: 60vw; /*optional*/
height: 60vh;
margin: 20vh auto;
background: #333;
}
<div class="container">
</div>
In case you know a defined sized for your div you could use calc.
Live example: https://jsfiddle.net/o8416eq3/
Notes: This works only if you hard coded the width and height of your ``div` in the CSS.
#target {
position:fixed;
top: calc(50vh - 100px/2);
left: calc(50vw - 200px/2);
width:200px;
height:100px;
background-color:red;
}
<div id='target'></div>
Using display:grid on parent and setting margin:auto to the centrerd elemnt will do the trick :
See below snippet :
html,body {
width :100%;
height:100%;
margin:0;
padding:0;
}
.container {
display:grid;
height:90%;
background-color:blue;
}
.content {
margin:auto;
color:white;
}
<div class="container">
<div class="content"> cented div here</div>
</div>
div {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
-ms-transform: translate(-50%, -50%); /* IE 9 */
-webkit-transform: translate(-50%, -50%); /* Chrome, Safari, Opera */
}
<body>
<div>Div to be aligned vertically</div>
</body>
position: absolute div in body document
An element with position: absolute; is positioned relative to the nearest positioned ancestor (instead of positioned relative to the viewport (body tag), like fixed).
However; if an absolute positioned element has no positioned ancestors, it uses the document body, and moves along with page scrolling.
source: CSS position
If you guys are using JQuery, you can do this by using .position();
<div class="positionthis"></div>
CSS
.positionthis {
width:100px;
height:100px;
position: absolute;
background:blue;
}
Javascript (JQuery)
$(document).ready(function () {
$('.positionthis').position({
of: $(document),
my: 'center center',
at: 'center center',
collision: 'flip flip'
});
});
JSFiddle : http://jsfiddle.net/vx9gV/
Is the browser supports it, using translate is powerful.
position: absolute;
background-color: red;
width: 70%;
height: 30%;
/* The translate % is relative to the size of the div and not the container*/
/* 21.42% = ( (100%-70%/2) / 0.7 ) */
/* 116.666% = ( (100%-30%/2) / 0.3 ) */
transform: translate3d( 21.42%, 116.666%, 0);
Sorry for late reply
best way is
div {
position: fixed;
top: 50%;
left: 50%;
margin-top: -50px;
margin-left: -100px;
}
margin-top and margin-left should be according to your div box size
Please use following CSS properties for center align element horizontally as well as vertically. This is worked fine for me.
div {
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0px;
margin: auto;
width: 100px;
height: 100px;
}
This solution worked for me
.middleDiv{
position : absolute;
height : 90%;
bottom: 5%;
}
(or height : 70% / bottom : 15%
height : 40% / bottom :30% ...)
I have a text container with paragraphs and headings. At the bottom of the page I want to float an image to the right of the page, while the text wraps around the image. The bottom of the image should be flush with the bottom of the last paragraph.
The page width is variable (responsive), but the image dimensions are fixed. Is it possible to accomplish this in HTML and CSS (CSS3 is fine)? If not, can it be done with a minimal amount of Javascript?
Here's a schematic example of what I want to accomplish:
The HTML currently looks something like this, but it can be changed if necessary. I don't particularly care where in the document the image is located. Using background images instead would be fine too.
<section>
<h2>...</h2>
<p>... ...</p>
<p>... ...</p>
...
<img src="...">
</section>
When I set float: right on the image, it floats to the right but I cannot get it to align to the bottom of the page. Suggestions?
Edit: the closest I got is this... :-)
Create a spacer element with float: right and height equal to the height of the content minus the height of the image. Then use float: right and clear: right on the image:
<div class="spacer"></div>
<img class="bottomRight" src="" />
<div class="content"></div>
.spacer {
height: calc(100% - 200px);
width: 0px;
float: right;
}
.bottomRight {
height: 200px;
float: right;
clear: right;
}
http://cssdesk.com/bLNWs
My demo uses fixed dimensions in the container element. Since that is rarely a realistic case, it probably makes more sense to use JavaScript to size the spacer. Call this function, passing a reference to the spacer element when the document is ready and during the window.onresize event.
function sizeSpacer(spacer) {
spacer.style.height = 0;
var container = spacer.parentNode;
var img = spacer.nextElementSibling || spacer.nextSibling;
var lastContentNode = container.children[container.children.length - 1];
var h = Math.max(0, container.clientHeight - img.clientHeight);
spacer.style.height = h + "px";
while (h > 0 && img.getBoundingClientRect().bottom > lastContentNode.getBoundingClientRect().bottom) {
spacer.style.height = --h + "px";
}
if (lastContentNode.getBoundingClientRect().bottom > img.getBoundingClientRect().bottom) {
spacer.style.height = ++h + "px";
}
}
This function works (see the demo), and can be reworked for jQuery or your library of choice. It's not meant to be plug-in quality code, but serves to illustrate the concept.
jsfiddle.net/gilly3/xLr7eacp
Edit: I created a jQuery plugin version (github | jsFiddle demo) that supports floating bottom left or bottom right. It also supports specifying which element to align the bottom with.
By the way, I didn't bother trying to support IE7.
I think the future way how to tackle this problem will be with CSS Exclusions.
CSS Exclusions extend the notion of content wrapping previously
limited to floats. ... Elements layout their inline content in their content area and wrap around the exclusion areas in their associated wrapping context (--excerpts from the spec)
This msdn article also explains exclusions
...web authors can now wrap text so that it completely surrounds
elements, thereby avoiding the traditional limitations of floats.
Instead of limiting elements to floating either to the left or right
relative to their position in the document flow, CSS Exclusions can be
positioned at a specified distance from the top, bottom, left, or
right sides of a containing block, while remaining part of the
document flow.
Ironically, to date this only works in IE10 (look for wrap-flow:both here)
Check out this fiddle in IE10+
This is what the code looks like:
<div class="container">
<div class="exclusion">
Exclusion positioned at bottom right hand side of text.
</div>
<div class="dummy_text">
<p>text here</p>
</div>
</div>
CSS
.container {
font-size: small;
background: aqua;
position: relative;
}
.exclusion {
-ms-wrap-flow: both;
-ms-wrap-margin: 10px;
z-index: 1;
position:absolute;
right:0;
bottom:0; /* try fiddling with this. For some reason bottom: -10px (or the like) works better here */
width: 150px;
height: 100px;
background: url(http://placehold.it/150x100) no-repeat;
}
So as you can see - even though the exclusion is positioned absolutely - it still acts like a float - in this case: float bottom right.
Regarding browser support:
Check out this site which shows which properties are supported by the browsers (to date: only IE10+ supports wrap-flow:both )
PS: Latest updates concerning CSS exclusions (and other simlar modules like CSS regions and CSS Shapes) can be found at the Adobe Web Platform Team Blog
Possible CSS Solution: (only tested in chrome)
It looks like this might work using CSS3's flex box properties and a combination of background-image properties. I was able to get it pretty close using only CSS. (It works but needs a little tweaking) Also, this may not be ideal cause I did have to change the markup a little bit to make this work. But its probably worth a shot if you are looking for a pure CSS solution.
Here is a Demo -> http://jsfiddle.net/ADSH2/
New Markup: (not to much different)
<section >
<h2>Some Heading:</h2>
<p>...</p>
<p class="last">
<span class="image"></span>
</p>
</section>
CSS:
.last {
display:inline-flex;
flex-direction:row;
}
.image {
padding:5px 0 0 5px;
width:100%;
background-image:url("http://dribbble.s3.amazonaws.com/users/200359/screenshots/758731/stackoverflow_logo.png");
background-size:100%;
background-repeat:no-repeat;
background-position:bottom right;
}
Resources:
http://css-tricks.com/snippets/css/a-guide-to-flexbox/
http://dev.w3.org/csswg/css-flexbox-1/
I have worked on a jQuery-based solution — probably not as elegant as the one posted by gilly3 though ;) and it's also slower and a bit bloated...
My trick is to append two <div>s to the section, which is floated to the left and hidden width a width of 0. One of the div, a designated ghost element that will have the same dimension as the image, will be positioned below another div that is the designated height spacer. The script uses a while loop to establish if the ghost element has reached the bottom of the parent section element. If this has not happened, it will increment the height of the height spacer by 1, until the condition is satisfied.
The markup I have used is as follow. I'm using the HTML5 attribute data-bottom-image to identify sections that you have the image to be floated to the bottom. Of course it is dispensable, depending on how you want to select for the correct section element.
<section id="c1" data-bottom-image>
<h2>...</h2>
<p>...</p>
<img src="http://placehold.it/250x100" />
</section>
And the jQuery script:
$(function () {
$("section > img:last-child").each(function () {
// Offset image based on the bottom and right padding of parent
var $par = $(this).parent();
$(this).css({
bottom: $par.css('padding-bottom'),
right: $par.css('padding-right')
});
});
// Function: adjust height of height-spacer, pixel by pixel
function adjustHeightSpacer($par, $hs, $is) {
// Stretch height spacer
$hs.height(0);
$hs.css({
height: $par.find("img").position().top - parseInt($par.css('padding-top'))
});
// Adjust height spacer
while($par.height() - $is.height() > $is.position().top - parseInt($par.css('padding-top'))) {
$hs.height("+=1");
}
while($par.height() - $is.height() < $is.position().top - parseInt($par.css('padding-top'))) {
$hs.height("-=1");
}
};
$("section[data-bottom-image]").each(function() {
// Append two spacers:
$(this).prepend('<div class="ghost height-spacer" /><div class="ghost image-spacer" />')
var $hs = $(this).find(".height-spacer"),
$is = $(this).find(".image-spacer");
// Adjust image spacer dimension
$is.css({
height: $(this).find("img").height(),
width: $(this).find("img").width()
});
// Adjust height spacer
adjustHeightSpacer($(this), $hs, $is);
});
$(window).resize($.debounce(250,function() {
$("section[data-bottom-image]").each(function() {
// Adjust height spacer
adjustHeightSpacer($(this), $(this).find(".height-spacer"), $(this).find(".image-spacer"));
});
}));
});
And here is the working Fiddle: http://jsfiddle.net/teddyrised/xmkAP/5/
I guess it's solved. It works!
With a little bit of JavaScript and CSS I did it like this:
http://jsfiddle.net/stichoza/aSScx/
One simple floatify() function.
Responsive.
Window resizing won't break it.
Any image width/height.
Put as many text you want.
Idea inspired by: http://www.csstextwrap.com/
CSS only Solution.
Using media queries one can accomplish this layout.
HTML
<section>
<h2>...</h2>
<p>... ...</p>
<p>... ...</p>
<img src="..." class="show-medium">
...
<img src="..." class="show-small">
</section>
CSS
html, body {
height: 100%;
width: 100%;
}
img {
display: none;
float: right;
clear: right;
}
#media (max-width: Xpx), (max-height: Xpx) {
/* show img for small screens */
.show-small { display:block; }
}
#media (min-width: Xpx) and (max-width: Xpx) and (min-height:Xpx) and (max-height: Xpx) {
/* show img for medium screens */
.show-medium { display:block; }
}
#media (min-width: Xpx) and (min-height: Xpx) {
/* show img as body background for large screens */
body {
background: url("http://placehold.it/200x300") no-repeat fixed right bottom transparent;
}
}
It plays well at different screen resolutions. See demo.
One has to play/adjust the CSS media queries as well as the position of the images within the markup in order to make it work.
CSS media queries is supported in Firefox 3.5+, Opera 7+, Safari 3+, Chrome and IE9+. For older IE versions one can use this fix: http://code.google.com/p/css3-mediaqueries-js/
A responsive solution for 2020, inspired by #gilly3's solution, and until CSS Exclusions arrive.
Flexbox on containing element to avoid needing fixed-height container whilst still ensuring 100% height works
:before element instead of spacer div
Viewport unit instead of fixed value to size image (and 'spacer') proportionately
To max-width image on wider screens, introduce breakpoint with fixed width to both image and spacer
Subtract any vertical margin needed within calc()
.container {
display: flex;
}
img {
float: right;
clear: right;
margin: 20px 0 0 20px;
height: 30vw;
#media (min-width: 1200px) {
height: 400px;
}
}
.container-inner:before {
content: "";
float: right;
height: calc(100% - 30vw - 20px);
#media (min-width: 1200px) {
height: calc(100% - 400px - 20px);
}
}
<div class="container">
<div class="container-inner">
<img src="https://picsum.photos/200" />
<p>Lorem ipsum dolor sit, amet consectetur adipisicing elit. Doloribus ab, doloremque quasi, obcaecati aspernatur nam possimus harum architecto odit molestiae pariatur aliquid necessitatibus, corrupti mollitia provident quis quam eligendi qui.</p>
<p>Lorem ipsum dolor sit, amet consectetur adipisicing elit. Doloribus ab, doloremque quasi, obcaecati aspernatur nam possimus harum architecto odit molestiae pariatur aliquid necessitatibus, corrupti mollitia provident quis quam eligendi qui.</p>
<p>Lorem ipsum dolor sit, amet consectetur adipisicing elit. Doloribus ab, doloremque quasi, obcaecati aspernatur nam possimus harum architecto odit molestiae pariatur aliquid necessitatibus, corrupti mollitia provident quis quam eligendi qui.</p>
<p>Lorem ipsum dolor sit, amet consectetur adipisicing elit. Doloribus ab, doloremque quasi, obcaecati aspernatur nam possimus harum architecto odit molestiae pariatur aliquid necessitatibus, corrupti mollitia provident quis quam eligendi qui.</p>
</div>
</div>
A CSS only and responsive solution that works without complex code. Resize the browser and see the magic in play:
.wrapper {
display: flex;
border: 1px solid;
}
.box {
text-align: justify;
font-size: 20px;
}
.float {
float: right;
height: 100%;
margin-left: 15px;
display: flex;
align-items: flex-end;
shape-outside: inset(calc(100% - 100px) 0 0);
}
<div class="wrapper">
<div class="box">
<div class="float"><img src="https://picsum.photos/id/1/100/100"></div>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam in dui quis orci ultricies aliquet nec sed enim. Mauris id rutrum nulla, et ornare leo. Donec aliquet malesuada tellus, eu laoreet lectus tincidunt ut. Quisque lacus magna, interdum eu urna
ac, aliquet gravida orci. Pellentesque gravida urna sit amet nulla suscipit, at venenatis lorem dignissim. Morbi quis nunc eu velit condimentum ornare. Curabitur finibus tincidunt ullamcorper. Pellentesque tincidunt et odio vitae tempus. Praesent
ac erat ut eros venenatis pulvinar. Pellentesque eu dapibus dui. Ut semper sed enim ut vestibulum. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce vitae elit eget velit porttitor consequat nec sed turpis. Proin libero nisl, egestas
hendrerit vulputate et, lobortis non nulla. Aenean dui libero, dictum vel nibh eget, tristique egestas enim.
</div>
</div>
More details: https://css-tricks.com/float-an-element-to-the-bottom-corner/
PS: I am the author of the above article
use this :
<section class="post">
<h2>...</h2>
<p>... ...</p>
<p>... ...</p>
...
<img src="...">
</section>
<style>
.post img {float:right;margin-top:80%}
</style>
change 80% to get best result.
Good Luck.
Here's a lightweight solution with a bit of jQuery:
http://jsfiddle.net/isherwood/6BvC2/
<section class="flagpole">
<div class="pole"></div>
<img class="flag" src="..." />
<p>Paragraphs...</p>
</section>
.pole, .flag {
float: right;
clear: right;
}
.pole {
width: 0.1px
}
function setFlag() {
$('section.flagpole').each(function () {
var poleHeight = $(this).height() - $(this).find('.flag').height();
$(this).find('.pole').height(poleHeight);
});
}
setFlag();
$(window).on('resize', function () {
setFlag();
});
To dispel any concerns about plagiarism, this solution is based on another similar answer I provided a while back.
Not quite there yet - but you might get where I'm going. Maybe someone else will complete this (if possible).
div.wrapper {
width: 300px;
transform: rotate(-90deg);
writing-mode: vertical-lr;
}
p.text {
margin-top: 1em;
writing-mode: vertical-lr;
}
img {
float: right;
transform: rotate(90deg);
height: 100px;
width: 100px;
}
<div class="wrapper">
<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAAAyCAYAAACqNX6+AAAAAXNSR0IArs4c6QAABCZJREFUeF7t3D9I80AUAPBXcFBwEQcRwcGl4KhLQTvXWQQHdRasWDroIEitxVVBRFCc/DO4ddRZhU5CwcWldCiVDiqFgkUEP9593HE5kjZNk/vTJouNudxd3u/eXYI2kWKx+AcAMDw8DENDQ/gx3CRH4Pv7GxqNBmk1Uq1W/wYHB6FWq5FfjI2NwcjIiOQu9WdzX19flrg3m83/IOPj4yQiYoEQJpiB4hTn9/d3KwhtPoSRC0FbcwQJYfwFcTvA24KEMN3BuIVwnSFidzptoLvLMfdsr3FynSEhjLvB4RXCc4aEMPYw3UL4BtLva4xfEL6D9BuM3xCBgfQ6TFAQgYP0GkzQENJATIeRBSEdxDQY2RDKQHSHUQWhHEQ3GNUQ2oCohtEFQjsQ2TC6QWgLEjSMrhDag/gNozuEMSDdwpgCYRxIpzCmQRgL0g7GVAjjQUSY399f8quBgQGj/43J818MaUBU/6QZEYIolnCamsIpSzKM24C7LSe5+22bM2bK8hpgr+e1jVxABbQH8SugftUTkAOrVluQoAIYVL1+QWkHIitgstrpFEobEFUBUtWuE5RyEF0Coks/lIHoEgBxpKrul3QQ1Rfsdk5X1U9pIKou0C2AUznZ/Q4cRPYFdQugGiYwEB0h8Juu6XQa1tbWYG5ujsX+9vYWVldXyf7NzQ2srKywY29vb7C8vAzFYhHW19chk8lAvV4nx52+HEvbOT8/Z/UcHBzA3t4e2RfrPD4+Zt9+9h1ERwgMAh+kp6cnBoLB2dragpOTExIs+jkajbJz4vE4LC4uEkz8jGCtrvPj4wM2Nzdhf38fsB5+o/2wqxPL+QaiKwQ/ImOxGJTLZTJSaYZgdjw+PgIdpblcDqampkjQeSwM7PPzM1xfX7OyWLfddeN5iHF6egqjo6MWkHZ1dg2iMwSNRKVSIR/xpQgYaB4EAXCj0wm/jwC4j2gYWH7/7OyM7NNj9/f3JIOOjo4gEolAPp+3wNG+tKoT2/AMYgKEuEDjVGIHQjMCy2OAS6USARIzQhz5FG9jY4PVOz09DZeXl7Czs8OaTyQSFlQ+y8Q6OwYxEYJGxm8QWt/DwwPwizZCIWoqlQJ8Q8bV1RV8fn6SjHl5ebFMe55BTIZoB+JlyqJrA2YUjng6dYlZiXErFApweHhIQH5+fhynQVdTVi9AtALhpygsJy7q/OJsN4XhXRlu8/PzbB0SUTALdnd3YXt7m9wE4JR2cXHB1iV+CuurV2vYTVleb3v529eFhQW2hszMzFhuj2m5iYkJAoYBx8V/dnaWPPtks1l2K21729tLGeFmUacLudsHQ5x2cMOg4kZvlzF7kskk3N3dweTkJDlOHwzxgZJ/+MNBsLS0BK+vr+ShE4/Rl/+wDAlfzyTyydkXE4C8nil8gZmc4LdqhX+B2T8GuESS5P5SHQAAAABJRU5ErkJggg==" />
<p class="text">
Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.
</p>
</div>