Div match height of smaller sibling - html

I have two divs side by side. The div on the left side is a basic navigation. The div on the right is an article. I want the div on the left to be the height of the viewport and the div on the right to hide anything that longer than the div on the left (the end goal is to have a stick side bar that takes up 1/3 of the screen). I’ve considered using flexbox, but haven’t used it before and wasn’t sure if this is the best method to go.
I tried setting the height of the left div to 100vh as suggested in this article: Make div 100% height of browser window but it didn’t work. I’ve seen suggestions regarding using tables but would prefer avoiding them. I’ve seen some suggestions regarding using jquery and having the right div resize itself based on the left, but this seems a little more complex then necessary.
Note: Most articles I've seen about matching div heights seems geared toward making the smaller div match the height of the larger. My issues is the opposite. I want the larger div to match the height of the smaller one and hide any extra content.
However I’m open to any suggestions.
<doctype="HTML">
<html>
<head>
<title>Web Hosting Issues</title>
<style>#import url('https://fonts.googleapis.com/css?family=Open+Sans');
</style>
</head>
<body>
<header>
<div id="logo">
<a href="home">
<h1>Website</h1>
<img>
</a>
</div>
<navigation>
<ul>
<div class="nav-row">
<li id="site-down">
<a href="site-down-url">
<img>Site Down
</a>
</li>
<li id="wordpress">
<a href="wordpress-url">
<img>Wordpress
</a>
</li>
</div>
<div class="nav-row">
<li id="migrations">
<a href="migrations-url">
<img>Migrations
</a>
</li>
<li id="backups">
<a href="backups-url">
<img>Backups
</a>
</li>
</div>
<div class="nav-row">
<li id="databases">
<img>Databases
</a>
</li>
<li id="domains">
<a href="domains-url">
<img>Domain
</a>
</li>
</div>
</ul>
</navigation>
<div id="contact-us">
<a href="contact-form">
<img>
<div>
<h2>Have Us Fix It</h2>
<button id="contact-button">Contact Us</button>
</div>
</a>
</div>
</header>
<article>
<h1>Article Title</h1>
<p>Lorem ipsum dolor sit amet, mei hinc graeci vituperatoribus et. Pri stet copiosae mediocrem eu. Mollis inimicus mel id, mutat mentitum vix an. No pro virtute intellegam, ea has epicurei referrentur, posse oporteat ius ei.</p>
<p>Libris appellantur et pro. Insolens ocurreret salutatus et sit. Mei ea aeque ludus aliquando, at hinc ponderum comprehensam cum. Eu nam mandamus expetenda dissentiunt, probo tacimates at eos, no everti docendi sed. Id appetere democritum nam.</p>
<p>Odio animal aperiam ea sit. Debet accumsan ne pro, eos simul perfecto invenire ea. Per ea quaestio consulatu. Eos vide repudiare id, mei cu ridens possim assentior, te probo intellegat vim. Has etiam incorrupte an. Id oratio verear audire mei, reque tincidunt duo ex.</p>
<p>Eum erant putant vocent ei. At dico exerci quo. Pri melius ocurreret persequeris in, eu noster virtute est. Aeque commodo ut duo. In sit melius dignissim, te has lorem minimum consectetuer.</p>
<p>Pri oratio vocibus vituperatoribus te, dolores persecuti sit ut. Esse munere eam ea, possim mentitum moderatius nec at. Doming gubergren ut mei, luptatum salutatus scriptorem mei an. Nec partem ponderum assueverit cu, veri erat libris his ad, ad vidisse docendi ius. At everti dolores disputationi vel, nec cu diceret eleifend. Pri cu falli erant, tamquam democritum ad sit, vis illum inani in. Apeirian nominati sed at, ei atomorum accommodare usu, has modus definitionem te.</p>
</article>
</body>
</html>
body {
font-family: 'Open Sans', sans-serif;
display: flex;
}
img {
max-width: 100%;
display: block;
margin: auto;
}
header {
float: left;
width: 50%;
}
header a {
text-decoration: none;
}
#logo, #contact-us {
background: #074f7b;
padding: 0.5em;
}
#logo h1 {
display: inline-block;
text-align: center;
font-family: sans-serif;
color: white;
float: left;
width: 68%;
}
#logo img {
float: left;
width: 30%;
padding-left: .4em;
color: white;
}
#logo::after{
content: " ";
display: block;
height: 0;
clear: both;
}
navigation {}
navigation:after {
visibility: hidden;
display: block;
content: "";
clear: both;
height: 0;
}
navigation ul {
margin: 0;
padding: 0;
}
.nav-row {}
.nav-row li {
width: 50%;
float: left;
display: inline-block;
min-height: 100px;
}
.nav-row a {
display: block;
padding: .5em;
text-align: center;
color: black;
}
.nav-row a:hover {
color: white;
}
#site-down {
background: #ffc219;
}
#wordpress {
background: #8f73b4;
}
#migrations {
background: #0778bb;
}
#backups {
background: #f06f26;
}
#databases {
background: #764821;
}
#domains {
background: #59bb53;
}
#contact-us h1, #contact-us img{
color: white;
}
#contact-us {
text-align: center;
}
#contact-us img {
float: left;
width: 45%;
text-align: center;
padding: 0 .5em
}
#contact-us div {
width: 50%;
float: left;
text-align: center;
}
#contact-us h2 {
color: white;
margin: 0em 0em .5em 0em;
padding-left: 0.625em
}
#contact-us::after{
content: " ";
display: block;
height: 0;
clear: both;
}
#contact-us button {
background: #8f73b4;
border-radius: .6em;
border: 1px solid #8f73b4;
color: white;
}
article {
float: right;
width: 50%;
}
article h1, article p {
margin: 1.563em;
}
article h1 {
text-align: center;
}

You could simply position:fixed; your left menu:
/*QuickReset*/*{box-sizing:border-box; margin:0;}html,body{height:100%;}
#menu{
position:fixed;
background: #8F73B4;
height:100%;
width: 33.333%;
}
#page{
margin-left:33.333%; /* matches the menu width */
height: 2000px; /* test: just to add scrollbars */
}
<div id="menu"> MENU BOXES HERE </div>
<div id="page"> PAGE CONTENT HERE </div>
Than for the menu elements/boxes I'd go with flexbox
JSBin demo
/*QuickReset*/
*{box-sizing:border-box;margin:0;}
html,body{height:100%;font:14px/1.4 sans-serif;}
.flex-col{
display: flex;
flex-flow: column wrap;
}
.flex-row{
display: flex;
flex-flow: row wrap;
}
.grow{
flex: 1;
}
img{
max-width:100%;
vertical-align:top;
}
#menu{
position:fixed;
background: #8F73B4;
height:100%;
width: 33.333%;
}
#page{
margin-left:33.333%; /* matches the menu width */
height: 2000px; /* test: just to add scrollbars */
}
<div id="menu" class="flex-col">
<header>header</header>
<div class="flex-row grow">
<div class="grow">1</div>
<div class="grow">2</div>
</div>
<div class="flex-row grow">
<div class="grow">3</div>
<div class="grow">4</div>
</div>
<footer>footer</footer>
</div>
<div id="page">
<h1>PAGE CONTENT HERE</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. At recusandae explicabo numquam molestiae, debitis eius deserunt cum necessitatibus aspernatur. Excepturi omnis, tenetur nihil voluptatibus hic incidunt doloribus itaque delectus dolorum!</p>
</div>
P.S: <navigation> is not a HTML5 element. You probably want to use <nav> for your semantic.

Related

Responsive HTML Menu - Centering Issue

I'm having a huge brain fart when trying to center my menu.
I would sincerely appreciate any help someone can offer me.
My menu continues to align on the left but it needs to be centered.
Whenever I put a container around it, I lose my responsive functionality.
Here is my HTML
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link href="./style.css" rel="stylesheet" type="text/css" />
<script>
/* Toggle between adding and removing the "responsive" class to topnav when the user clicks on the icon */
function myFunction() {
var x = document.getElementById("myTopnav");
if (x.className === "topnav") {
x.className += " responsive";
} else {
x.className = "topnav";
}
}
</script>
</head>
<body>
<div id="header">
<div class="logo"><img src="./images/logo.png"></div>
<div class="topnav" id="myTopnav">
Home
<div class="dropdown">
<button class="dropbtn">Gifts
<i class="fa fa-caret-down"></i>
</button>
<div class="dropdown-content">
Link 1
Link 2
Link 3
</div>
</div>
<div class="dropdown">
<button class="dropbtn">Home & Lifestyle
<i class="fa fa-caret-down"></i>
</button>
<div class="dropdown-content">
Link 1
Link 2
Link 3
</div>
</div>
<div class="dropdown">
<button class="dropbtn">Edible
<i class="fa fa-caret-down"></i>
</button>
<div class="dropdown-content">
Link 1
Link 2
Link 3
</div>
</div>
<div class="dropdown">
<button class="dropbtn">Wearable
<i class="fa fa-caret-down"></i>
</button>
<div class="dropdown-content">
Link 1
Link 2
Link 3
</div>
</div>
<div class="dropdown">
<button class="dropbtn">Toys & Games
<i class="fa fa-caret-down"></i>
</button>
<div class="dropdown-content">
Link 1
Link 2
Link 3
</div>
</div>
<div class="dropdown">
<button class="dropbtn">Blog
<i class="fa fa-caret-down"></i>
</button>
<div class="dropdown-content">
Link 1
Link 2
Link 3
</div>
</div>
<div class="dropdown">
<button class="dropbtn">About Us
<i class="fa fa-caret-down"></i>
</button>
<div class="dropdown-content">
Link 1
Link 2
Link 3
</div>
</div>
☰
</div>
</div>
<!-- END TOP NAV -->
</div>
<!-- END HEADER -->
Here is my CSS
body {
margin:0 auto;
}
.container {
overflow: hidden;
width: 960px;
margin: 0 auto;
}
.logo {
display: block;
color: #000000;
text-align: center;
letter-spacing: .04em;
font-family: 'Quattrocento Sans', sans-serif;
font-size: 40px;
font-weight: 700;
line-height: normal;
padding: 10px 0;
}
.nav-wrap {
overflow: hidden;
width: 100%;
padding: 10px 0;
background: #ffffff;
box-sizing: border-box;
-webkit-backface-visibility: hidden;
text-align:center;
}
/* Add a black background color to the top navigation */
.topnav {
background-color: #fff;
overflow: hidden;
}
/* Style the links inside the navigation bar */
.topnav a {
float: left;
display: block;
color: #b9b9b9;
text-align: center;
padding: 14px 16px;
text-decoration: none;
text-transform: uppercase;
letter-spacing: .07em;
font-family: 'Quattrocento Sans', sans-serif;
font-size: 14px;
font-weight: 400;
line-height: 19px;
}
/* Add an active class to highlight the current page */
.active {
color: 000;
}
/* Hide the link that should open and close the topnav on small screens */
.topnav .icon {
display: none;
color:#b9b9b9;
}
/* Dropdown container - needed to position the dropdown content */
.dropdown {
float: left;
overflow: hidden;
}
/* Style the dropdown button to fit inside the topnav */
.dropdown .dropbtn {
text-transform: uppercase;
letter-spacing: .07em;
font-weight: 400;
line-height: 19px;
font-size:inherit;
border: none;
outline: none;
color: #b9b9b9;
padding: 14px 16px;
background-color: inherit;
font-family: inherit;
margin: 0;
}
/* Style the dropdown content (hidden by default) */
.dropdown-content {
display: none;
position: absolute;
background-color: #f9f9f9;
min-width: 160px;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
z-index: 1;
}
/* Style the links inside the dropdown */
.dropdown-content a {
float: none;
color: #b9b9b9;
padding: 12px 16px;
text-decoration: none;
display: block;
text-align: left;
}
/* Add a dark background on topnav links and the dropdown button on hover */
.topnav a:hover, .dropdown:hover .dropbtn {
color: 000;
}
/* Add a grey background to dropdown links on hover */
.dropdown-content a:hover {
background-color: #ddd;
color: black;
}
/* Show the dropdown menu when the user moves the mouse over the dropdown button */
.dropdown:hover .dropdown-content {
display: block;
}
/* When the screen is less than 600 pixels wide, hide all links, except for the first one ("Home"). Show the link that contains should open and close the topnav (.icon) */
#media screen and (max-width: 600px) {
.topnav a:not(:first-child), .dropdown .dropbtn {
display: none;
}
.topnav a.icon {
float: right;
display: block;
}
}
/* The "responsive" class is added to the topnav with JavaScript when the user clicks on the icon. This class makes the topnav look good on small screens (display the links vertically instead of horizontally) */
#media screen and (max-width: 600px) {
.topnav.responsive {position: relative;}
.topnav.responsive a.icon {
position: absolute;
right: 0;
top: 0;
}
.topnav.responsive a {
float: none;
display: block;
text-align: left;
}
.topnav.responsive .dropdown {float: none;}
.topnav.responsive .dropdown-content {position: relative;}
.topnav.responsive .dropdown .dropbtn {
display: block;
width: 100%;
text-align: left;
}
}
p {font-family: Verdana, Arial, Helvetica, sans-serif; font-size:14px; color:#333; line-height:20px;}
.thick { font-weight: bold;}
.column {
float: left;
width: 285px;
padding: 15px;
}
.row {
width: 945px;
margin: 0 auto;
text-align: center;
}
/* Clear floats after image containers */
.row::after {
content: "";
clear: both;
display: table;
}
hr.short {
width: 285px;
height: 1px;
border: none;
background-color: #dedede;
margin-top: 40px;
}
/* Responsive layout */
#media only screen and (max-width: 767px) {
.column {
width: 100%;
padding: 0px;
}
.row {
width: 100%;
margin: 0 auto;
text-align: center;
}
/* Clear floats after image containers */
.row::after {
content: "";
clear: both;
display: table;
}
}
The menu keeps going to the left (probably the float:left) but I just can't get this to work.
Anyone able to be my hero for the day, please?
You could use flexbox to center your menu:
.topnav {
display: flex;
flex-wrap: wrap;
justify-content: center;
}
#media screen and (max-width: 600px) {
.topnav {
justify-content: space-between;
}
.responsive {
flex-direction: column;
}
}
EDIT:
As you were struggling to implement your desired solution despite my suggestions, and as I had some spare time today, I decided to prepare a minimal working example for you. I think you wanted to achieve something like this:
.logo-placeholder {
width: 50px;
height: 30px;
margin: auto;
background-color: red;
margin-bottom: 10px;
}
.content {
margin: 20px 100px 0 100px;
padding: 20px;
background-color: #EEE;
}
.header-navigation {
position: sticky;
top: 0;
padding: 5px;
background-color: #CCC;
}
.navigation {
display: flex;
justify-content: space-around;
list-style: none;
}
.subnavigation {
display: none;
}
.navigation-item {
position: relative;
}
.navigation-item:hover > .subnavigation {
display: block;
position: absolute;
list-style: none;
padding: 10px;
background-color: #EEE;
}
<div class="logo-placeholder"></div>
<nav class="header-navigation">
<ul class="navigation">
<li class="navigation-item">
Top Nav Item 1
<ul class="subnavigation">
<li>Subitem 1</li>
<li>Subitem 2</li>
<li>Subitem 3</li>
<li>Subitem 4</li>
</ul>
</li>
<li class="navigation-item">
Top Nav Item 2
<ul class="subnavigation">
<li>Subitem 1</li>
<li>Subitem 2</li>
<li>Subitem 3</li>
<li>Subitem 4</li>
</ul>
</li>
<li class="navigation-item">
Top Nav Item 3
<ul class="subnavigation">
<li>Subitem 1</li>
<li>Subitem 2</li>
<li>Subitem 3</li>
<li>Subitem 4</li>
</ul>
</li>
<li class="navigation-item">
Top Nav Item 4
<ul class="subnavigation">
<li>Subitem 1</li>
<li>Subitem 2</li>
<li>Subitem 3</li>
<li>Subitem 4</li>
</ul>
</li>
</ul>
</nav>
<article class="content">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quid ergo aliud intellegetur nisi uti ne quae pars naturae neglegatur? Quamquam ab iis philosophiam et omnes ingenuas disciplinas habemus; Sin laboramus, quis est, qui alienae modum statuat industriae? <b>Duo Reges: constructio interrete.</b> Idem iste, inquam, de voluptate quid sentit? Hoc etsi multimodis reprehendi potest, tamen accipio, quod dant. <b>Maximus dolor, inquit, brevis est.</b> </p>
<p><i>Non est igitur summum malum dolor.</i> <i>Sed haec omittamus;</i> Quia nec honesto quic quam honestius nec turpi turpius. Quid Zeno? </p>
<p>Eiuro, inquit adridens, iniquum, hac quidem de re; An me, inquam, nisi te audire vellem, censes haec dicturum fuisse? Cenasti in vita numquam bene, cum omnia in ista Consumis squilla atque acupensere cum decimano. At ille non pertimuit saneque fidenter: Istis quidem ipsis verbis, inquit; Est autem etiam actio quaedam corporis, quae motus et status naturae congruentis tenet; Quas enim kakaw Graeci appellant, vitia malo quam malitias nominare. </p>
<p>Nam si beatus umquam fuisset, beatam vitam usque ad illum a Cyro extructum rogum pertulisset. Semper enim ex eo, quod maximas partes continet latissimeque funditur, tota res appellatur. Eam tum adesse, cum dolor omnis absit; An me, inquam, nisi te audire vellem, censes haec dicturum fuisse? </p>
<p>Nam quibus rebus efficiuntur voluptates, eae non sunt in potestate sapientis. Immo istud quidem, inquam, quo loco quidque, nisi iniquum postulo, arbitratu meo. <i>Sed nunc, quod agimus;</i> Aliter homines, aliter philosophos loqui putas oportere? Universa enim illorum ratione cum tota vestra confligendum puto. Sed potestne rerum maior esse dissensio? An ea, quae per vinitorem antea consequebatur, per se ipsa curabit? <b>Quod quidem nobis non saepe contingit.</b> Dolor ergo, id est summum malum, metuetur semper, etiamsi non aderit; Nunc ita separantur, ut disiuncta sint, quo nihil potest esse perversius. </p>
<p>Sed quid attinet de rebus tam apertis plura requirere? Claudii libidini, qui tum erat summo ne imperio, dederetur. <i>Et ille ridens: Video, inquit, quid agas;</i> <b>Hoc est non dividere, sed frangere.</b> Tu enim ista lenius, hic Stoicorum more nos vexat. <b>Quid iudicant sensus?</b> Facile est hoc cernere in primis puerorum aetatulis. Sit enim idem caecus, debilis. Tum ille timide vel potius verecunde: Facio, inquit. <i>Comprehensum, quod cognitum non habet?</i> </p>
<p>Cur ipse Pythagoras et Aegyptum lustravit et Persarum magos adiit? Dicet pro me ipsa virtus nec dubitabit isti vestro beato M. Aliter enim nosmet ipsos nosse non possumus. Re mihi non aeque satisfacit, et quidem locis pluribus. Scio enim esse quosdam, qui quavis lingua philosophari possint; Familiares nostros, credo, Sironem dicis et Philodemum, cum optimos viros, tum homines doctissimos. </p>
<p>Atque hoc loco similitudines eas, quibus illi uti solent, dissimillimas proferebas. Murenam te accusante defenderem. Cupiditates non Epicuri divisione finiebat, sed sua satietate. An vero, inquit, quisquam potest probare, quod perceptfum, quod. Huic ego, si negaret quicquam interesse ad beate vivendum quali uteretur victu, concederem, laudarem etiam; <b>Quae cum essent dicta, discessimus.</b> Quod maxime efficit Theophrasti de beata vita liber, in quo multum admodum fortunae datur. </p>
<p>Zenonis est, inquam, hoc Stoici. Itaque vides, quo modo loquantur, nova verba fingunt, deserunt usitata. <i>Aliter enim nosmet ipsos nosse non possumus.</i> Nec tamen ullo modo summum pecudis bonum et hominis idem mihi videri potest. Quid enim est a Chrysippo praetermissum in Stoicis? Alterum significari idem, ut si diceretur, officia media omnia aut pleraque servantem vivere. <i>Qui ita affectus, beatum esse numquam probabis;</i> Itaque si aut requietem natura non quaereret aut eam posset alia quadam ratione consequi. </p>
<p>Itaque sensibus rationem adiunxit et ratione effecta sensus non reliquit. Multoque hoc melius nos veriusque quam Stoici. Est enim effectrix multarum et magnarum voluptatum. <b>Nihilo beatiorem esse Metellum quam Regulum.</b> Nos autem non solum beatae vitae istam esse oblectationem videmus, sed etiam levamentum miseriarum. </p>
<p>Quaerimus enim finem bonorum. Tenent mordicus. At iam decimum annum in spelunca iacet. Cur tantas regiones barbarorum pedibus obiit, tot maria transmisit? </p>
<p>Cum audissem Antiochum, Brute, ut solebam, cum M. Summum ením bonum exposuit vacuitatem doloris; Aliis esse maiora, illud dubium, ad id, quod summum bonum dicitis, ecquaenam possit fieri accessio. Et ille ridens: Video, inquit, quid agas; Sed fortuna fortis; Facillimum id quidem est, inquam. Quid in isto egregio tuo officio et tanta fide-sic enim existimo-ad corpus refers? Eorum enim est haec querela, qui sibi cari sunt seseque diligunt. Sic enim maiores nostri labores non fugiendos tristissimo tamen verbo aerumnas etiam in deo nominaverunt. Quod autem ratione actum est, id officium appellamus. <b>Sin aliud quid voles, postea.</b> </p>
</article>
As my account is fairly new, I couldn't comment, but here it is anyway:
ajobi posted a nice solution and that is a great one for 2D rows of elements. You should take a look at CSS Grid as well. It does basically the same as Flexbox, but in 3 dimensions.

Horizontally and vertically center the image [duplicate]

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% ...)

Floating an Image in a way it slides out of the div

I want to float an image in that way it slides out of the div. I have even added the negative margin for the image but what is happening is that the iPhone image is getting truncated all the time.
I have tried to include the height and width of the image as well but nothing is working.
Please help.
.blue-wrapper {
background: #41A7D3;
width: 100%;
overflow: hidden;
}
.blue {
width: 1000px;
margin: 0 auto;
padding: 0;
}
.blue-left {
float: left;
width: 39%;
}
.blue-left img {
display: block;
margin-top: -100px;
width: 380px;
height: 739px;
}
.blue-right {
float: right;
width: 61%;
color: #FFFFFF;
}
<div class="blue-wrapper">
<div class="blue">
<div class="blue-left">
<img src="https://feverweb.s3.amazonaws.com/landing/images/iphone-white.png" alt="3rd iPhone">
</div>
<!-- Blue Left -->
<div class="blue-right">
<div class="blue-text">
<h2>What ComeAgain Can Do for Your Business</h2>
<p>Lorem ipsum dolor sit amet, id sonet conclusionemque mel, denique nominavi instructior at mea. Ea utamur persecuti vis. Omnes perfecto menandri est ut, quot nonumy vix at. Et vix vocent corrumpit definiebas. Ut legere vocibus fierent nec, ei dicit
everti patrioque sed. Mel verear impetus et, fugit vocent ut nam.
</p>
<h3>How ComeAgain Works</h3>
<ul>
<li>You always get a Reward with your 1st Purchase at any ComeAgain Location!</li>
<li>Then ComeAgain… when you fill up a Rewards Card, you get a Free Reward!</li>
</ul>
</div>
<!-- Blue Text -->
<div class="blue-button">
Get Registered
</div>
<!-- Blue Button -->
</div>
<!-- Blue Right -->
</div>
<!-- Blue -->
</div>
<!-- Blue Wrapper -->
.blue-wrapper {
background: #41A7D3;
width: 100%;
}
.blue {
width: 1000px;
margin: 0 auto;
padding: 0;
}
.blue-left {
float: left;
width: 39%;
position: relative;
}
.blue-left img {
display: block;
top: 100px;
width: 380px;
height: 739px;
position: absolute;
}
.blue-right {
float: right;
width: 61%;
color: #FFFFFF;
}
.clearfix:after {
visibility: hidden;
display: block;
font-size: 0;
content: " ";
clear: both;
height: 0;
}
.clearfix { display: inline-block; }
/* start commented backslash hack \*/
* html .clearfix { height: 1%; }
.clearfix { display: block; }
/* close commented backslash hack */
<div class="blue-wrapper clearfix">
<div class="blue">
<div class="blue-left">
<img src="https://feverweb.s3.amazonaws.com/landing/images/iphone-white.png" alt="3rd iPhone">
</div><!-- Blue Left -->
<div class="blue-right">
<div class="blue-text">
<h2>What ComeAgain Can Do for Your Business</h2>
<p>Lorem ipsum dolor sit amet, id sonet conclusionemque mel, denique nominavi instructior at mea.
Ea utamur persecuti vis.
Omnes perfecto menandri est ut, quot nonumy vix at. Et vix vocent corrumpit definiebas.
Ut legere vocibus fierent nec, ei dicit everti patrioque sed. Mel verear impetus et, fugit vocent ut nam.
</p>
<h3>How ComeAgain Works</h3>
<ul>
<li>You always get a Reward with your 1st Purchase at any ComeAgain Location!</li>
<li>Then ComeAgain… when you fill up a Rewards Card, you get a Free Reward!</li>
</ul>
</div><!-- Blue Text -->
<div class="blue-button">
Get Registered
</div><!-- Blue Button -->
</div><!-- Blue Right -->
</div><!-- Blue -->
</div><!-- Blue Wrapper -->
For the background you should add a .clearfix on the wrapper.

How to horizontally align 2 div containing columns of text?

I'm working on a horizontal scrolling website and I'm trying to align 2 divs with columns of text.
I can't manage to align these 2 divs (the second one is at the bottom left of the first one) and some of the columns are outside the div.
How can I resolve this?
HTML:
<body>
<div id="main">
<div id="content">
<div id="article"><!-- columns of text --></div>
<div id="comments"><!-- columns of text --></div>
</div>
</div>
</body>
CSS:
body {
margin: 0;
padding: 0;
color: white;
background: transparent;
}
#main {
position: absolute;
height: 100%;
top: 0;
left: 0;
}
#content {
overflow-x: scroll;
overflow-y: auto;
height: 100%;
top: 0;
left: 0;
background: black;
}
#article {
border: 10px solid yellow;
float: left;
width: 100%;
height: 100%;
position: relative;
box-sizing: border-box;
font-size: 25px;
text-align: left;
-webkit-column-width: 300px;
-webkit-column-gap: 40px;
-moz-column-width: 300px;
-moz-column-gap: 40px;
column-width: 300px;
column-gap: 40px;
background: green;
}
#comments {
border: 10px solid red;
float: left;
width: 100%;
height: 100%;
position: relative;
box-sizing: border-box;
font-size: 25px;
text-align: left;
-webkit-column-width: 300px;
-webkit-column-gap: 40px;
-moz-column-width: 300px;
-moz-column-gap: 40px;
column-width: 300px;
column-gap: 40px;
background: blue;
}
Here is the JSFiddle demo : http://jsfiddle.net/kz5ch49w/54/
<body>
<div id="main">
<div id="content">
<div id="article"><!-- columns of text --></div>
<div id="comments"><!-- columns of text --></div>
</div>
</div>
</body>
css:
body { margin:0; padding:0; color:white; background:transparent;width:auto }
div { position:absolute;margin:1%;}
Use absolute position and calculate width and left position serially. So you can use horizontal scrolling. Eg : http://jsfiddle.net/kz5ch49w/57/
Try this. It makes each box have equal width (by the 50% width defined in the CSS) and you can change 2000px to whatever screen size you want. I made it 2000px on my test to give me a reason to scroll and because 2000 exceeds my screen width.
<html>
<title>x</title>
<head>
<style>
body { margin:0; padding:0; color:white; background:transparent; }
#main {width:2000px;}
#article {border:10px solid yellow; float:left; width:50%; height:100%; box-sizing: border-box; font-size:25px; text-align:left; -webkit-column-width: 300px; -webkit-column-gap: 40px; -moz-column-width: 300px; -moz-column-gap: 40px; column-width: 300px; column-gap: 40px; background:green; }
#comments {border:10px solid red; float:right; width:50%; height:100%; box-sizing: border-box; font-size:25px; text-align:left; -webkit-column-width: 300px; -webkit-column-gap: 40px; -moz-column-width: 300px; -moz-column-gap: 40px; column-width: 300px; column-gap: 40px; background:blue; }
</style>
</head>
<body>
<div id="main">
<div id="article"><p>dsgkhskgshgk</p><p>dkjghskgdhskgh</p></div>
<div id="comments"><p>dsgkhskgshgk</p><p>dkjghskgdhskgh</p></div>
</div>
</body>
</html>
I update your jsfiddle where I changed CSS properties. like position , height , width.
http://jsfiddle.net/kz5ch49w/58/
As your 62 jsfiddle:- I update fiddle :- http://jsfiddle.net/kz5ch49w/64/
Check for the responsive by changing browser or fiddle height, width or add or modify content.
what you need to do, never give hardcore height , width. you can give 50% width , float:left for both div when you want horizontally set. or you can set width 33% of 3 div, if you wish to set horizontally. means your div will set in 100% width by-default, you can set float left will set to left and width will use for its content.
As your requirement never use position and -moz... (this is default add by mozila browser), each browser have its own content properties, when we not give anything, every browser add properties itself which same properties may you not get in another browser.
Give always % based height width for responsive, never though about content height, it will automatically scroll down if you give % width or not give the width(in this case it take browser width or parent div width(if you given)).
I think, I explain you better.
Update HTML
<html>
<head>
<style>
body {
margin: 0;
padding: 0;
color: white;
background: transparent;
}
#main {
position: absolute;
height: 100%;
top: 0;
left: 0;
}
#content {
overflow-x: scroll;
overflow-y: auto;
height: 100%;
top: 0;
left: 0;
background: black;
}
#article {
border: 10px solid yellow;
float: left;
width: 50%;
/*height: 100%;
position: relative;*/
box-sizing: border-box;
font-size: 25px;
text-align: left;
/*-webkit-column-width: 300px;
-webkit-column-gap: 40px;
-moz-column-width: 300px;
-moz-column-gap: 40px;
column-width: 300px;
column-gap: 40px;*/
background: green;
}
#comments {
border: 10px solid red;
float: left;
width: 50%;
/*height: 100%;
position: relative;*/
box-sizing: border-box;
font-size: 25px;
text-align: left;
/*-webkit-column-width: 300px;
-webkit-column-gap: 40px;
-moz-column-width: 300px;
-moz-column-gap: 40px;
column-width: 300px;
column-gap: 40px;*/
background: blue;
}
</style>
</head>
<body>
<div id="main">
<div id="content">
<div id="article">
<p>Sed (saepe enim redeo ad Scipionem, cuius omnis sermo erat de amicitia) querebatur, quod omnibus in rebus homines diligentiores essent; capras et oves quot quisque haberet, dicere posse, amicos quot haberet, non posse dicere et in illis quidem parandis adhibere curam, in amicis eligendis neglegentis esse nec habere quasi signa quaedam et notas, quibus eos qui ad amicitias essent idonei, iudicarent. Sunt igitur firmi et stabiles et constantes eligendi; cuius generis est magna penuria. Et iudicare difficile est sane nisi expertum; experiendum autem est in ipsa amicitia. Ita praecurrit amicitia iudicium tollitque experiendi potestatem.</p>
<p>Equitis Romani autem esse filium criminis loco poni ab accusatoribus neque his iudicantibus oportuit neque defendentibus nobis. Nam quod de pietate dixistis, est quidem ista nostra existimatio, sed iudicium certe parentis; quid nos opinemur, audietis ex iuratis; quid parentes sentiant, lacrimae matris incredibilisque maeror, squalor patris et haec praesens maestitia, quam cernitis, luctusque declarat.</p>
<p>Et hanc quidem praeter oppida multa duae civitates exornant Seleucia opus Seleuci regis, et Claudiopolis quam deduxit coloniam Claudius Caesar. Isaura enim antehac nimium potens, olim subversa ut rebellatrix interneciva aegre vestigia claritudinis pristinae monstrat admodum pauca.</p>
<p>Ego vero sic intellego, Patres conscripti, nos hoc tempore in provinciis decernendis perpetuae pacis habere oportere rationem. Nam quis hoc non sentit omnia alia esse nobis vacua ab omni periculo atque etiam suspicione belli?</p>
<p>Quibus ita sceleste patratis Paulus cruore perfusus reversusque ad principis castra multos coopertos paene catenis adduxit in squalorem deiectos atque maestitiam, quorum adventu intendebantur eculei uncosque parabat carnifex et tormenta. et ex is proscripti sunt plures actique in exilium alii, non nullos gladii consumpsere poenales. nec enim quisquam facile meminit sub Constantio, ubi susurro tenus haec movebantur, quemquam absolutum.</p>
<p>Sed laeditur hic coetuum magnificus splendor levitate paucorum incondita, ubi nati sunt non reputantium, sed tamquam indulta licentia vitiis ad errores lapsorum ac lasciviam. ut enim Simonides lyricus docet, beate perfecta ratione vieturo ante alia patriam esse convenit gloriosam.</p>
<p>Exsistit autem hoc loco quaedam quaestio subdifficilis, num quando amici novi, digni amicitia, veteribus sint anteponendi, ut equis vetulis teneros anteponere solemus. Indigna homine dubitatio! Non enim debent esse amicitiarum sicut aliarum rerum satietates; veterrima quaeque, ut ea vina, quae vetustatem ferunt, esse debet suavissima; verumque illud est, quod dicitur, multos modios salis simul edendos esse, ut amicitiae munus expletum sit.</p>
<p>Figgeri, inquam, Triari, nullo pacto potest, ut non dicas, quid non probes eius, a quo dissentias. quid enim me prohiberet Epicureum esse, si probarem, quae ille diceret? cum praesertim illa perdiscere ludus esset. Quam ob rem dissentientium inter se reprehensiones non sunt vituperandae, maledicta, contumeliae, tum iracundiae, contentiones concertationesque in disputando pertinaces indignae philosophia mihi videri solent.</p>
</div>
<div id="comments">
<p>Sed (saepe enim redeo ad Scipionem, cuius omnis sermo erat de amicitia) querebatur, quod omnibus in rebus homines diligentiores essent; capras et oves quot quisque haberet, dicere posse, amicos quot haberet, non posse dicere et in illis quidem parandis adhibere curam, in amicis eligendis neglegentis esse nec habere quasi signa quaedam et notas, quibus eos qui ad amicitias essent idonei, iudicarent. Sunt igitur firmi et stabiles et constantes eligendi; cuius generis est magna penuria. Et iudicare difficile est sane nisi expertum; experiendum autem est in ipsa amicitia. Ita praecurrit amicitia iudicium tollitque experiendi potestatem.</p>
<p>Equitis Romani autem esse filium criminis loco poni ab accusatoribus neque his iudicantibus oportuit neque defendentibus nobis. Nam quod de pietate dixistis, est quidem ista nostra existimatio, sed iudicium certe parentis; quid nos opinemur, audietis ex iuratis; quid parentes sentiant, lacrimae matris incredibilisque maeror, squalor patris et haec praesens maestitia, quam cernitis, luctusque declarat.</p>
<p>Et hanc quidem praeter oppida multa duae civitates exornant Seleucia opus Seleuci regis, et Claudiopolis quam deduxit coloniam Claudius Caesar. Isaura enim antehac nimium potens, olim subversa ut rebellatrix interneciva aegre vestigia claritudinis pristinae monstrat admodum pauca.</p>
<p>Ego vero sic intellego, Patres conscripti, nos hoc tempore in provinciis decernendis perpetuae pacis habere oportere rationem. Nam quis hoc non sentit omnia alia esse nobis vacua ab omni periculo atque etiam suspicione belli?</p>
<p>Quibus ita sceleste patratis Paulus cruore perfusus reversusque ad principis castra multos coopertos paene catenis adduxit in squalorem deiectos atque maestitiam, quorum adventu intendebantur eculei uncosque parabat carnifex et tormenta. et ex is proscripti sunt plures actique in exilium alii, non nullos gladii consumpsere poenales. nec enim quisquam facile meminit sub Constantio, ubi susurro tenus haec movebantur, quemquam absolutum.</p>
<p>Sed laeditur hic coetuum magnificus splendor levitate paucorum incondita, ubi nati sunt non reputantium, sed tamquam indulta licentia vitiis ad errores lapsorum ac lasciviam. ut enim Simonides lyricus docet, beate perfecta ratione vieturo ante alia patriam esse convenit gloriosam.</p>
<p>Exsistit autem hoc loco quaedam quaestio subdifficilis, num quando amici novi, digni amicitia, veteribus sint anteponendi, ut equis vetulis teneros anteponere solemus. Indigna homine dubitatio! Non enim debent esse amicitiarum sicut aliarum rerum satietates; veterrima quaeque, ut ea vina, quae vetustatem ferunt, esse debet suavissima; verumque illud est, quod dicitur, multos modios salis simul edendos esse, ut amicitiae munus expletum sit.</p>
<p>Figgeri, inquam, Triari, nullo pacto potest, ut non dicas, quid non probes eius, a quo dissentias. quid enim me prohiberet Epicureum esse, si probarem, quae ille diceret? cum praesertim illa perdiscere ludus esset. Quam ob rem dissentientium inter se reprehensiones non sunt vituperandae, maledicta, contumeliae, tum iracundiae, contentiones concertationesque in disputando pertinaces indignae philosophia mihi videri solent.</p>
</div>
</div>
</div>
</body>
</html>
Make the following changes to your CSS. This will align the two divs horizontally with respect to each other:
CSS:
#main {
left: 0;
position: relative;
top: 0;
}
#content {
background: none repeat scroll 0 0 black;
left: 0;
overflow-x: scroll;
top: 0;
width: 100%;
}
#article {
background: none repeat scroll 0 0 green;
border: 10px solid yellow;
box-sizing: border-box;
float: left;
font-size: 25px;
height: 100%;
position: relative;
text-align: left;
width: 50%;
}
#comments {
background: none repeat scroll 0 0 blue;
border: 10px solid red;
box-sizing: border-box;
float: left;
font-size: 25px;
position: relative;
text-align: left;
width: 50%;
}
This is similar to another question I answered, except the other person had 3 divs he wanted horizontally aligned.
Your options are:
Add this to your css:
#articles,#comments {display: inline-block;}
Change the inner-most divs to spans and add this to your CSS:
#articles, #comments {display: block;}

How to stop grid from collapsing in on itself when browser window is resized?

I'm creating a website to showcase some of my work and I've run into a problem with the grid collapsing when I resize the browser window to a smaller size.
I'm still very much a noob at coding since I just started learning html and css a week ago, so I can't figure out how to fix it. I've tried various techniques that I've found to similar problems, to no avail. Oh, and I'm using the bootstrap framework if that helps. Here's the html and css codes:
html:
<body>
<div class="container">
<!-- Header begin -->
<div class="row">
<div id="divider1a" class="span12">divider1a</div>
</div>
<div class="row">
<div id="divider1b" class="span12">divider1b</div>
</div>
<div class="row">
<div id="head" class="span12">
<div class="row">
<div id="logo" class="span4"><img src="images/Logo.png" width="305" height="100" /></div>
<div id="socialmedia" class="span8"><ul>
<li><img src="images/rss.png" width="48" height="48" /></li>
<li><img src="images/linkedin.png" width="48" height="48" /></li>
<li><img src="images/vimeo.png" width="48" height="48" /></li>
<li><img src="images/youtube.png" width="48" height="48" /></li>
</ul></div>
<div id="navbar" class="span8"><ul>
<li>About</li>
<li>Demo Reel</li>
<li>Portfolio</li>
<li>Contact</li>
</ul></div>
</div>
</div>
</div>
<!-- Header end -->
<!-- Middle begin -->
<div class="row">
<div id="divider2a" class="span12">divider2a</div>
</div>
<div class="row">
<div id="divider2b" class="span12">divider2b</div>
</div>
<div class="row">
<div id="imgbanner" class="span12"><img src="images/imgbanner_comingsoon.png" /></div>
</div>
<div class="row">
<div id="slidebanner" class="span12">
<div class="row">
<div id="arrowleft" class="span3"><img src="images/arrowleft_comingsoon.png" /></div>
<div id="imgslide" class="span2"><img src="images/imgsquare_comingsoon.png" /></div>
<div id="imgslide" class="span2"><img src="images/imgsquare_comingsoon.png" /></div>
<div id="imgslide" class="span2"><img src="images/imgsquare_comingsoon.png" /></div>
<div id="arrowright" class="span3"><img src="images/arrowright_comingsoon.png" /></div>
</div>
</div>
</div>
<div class="row">
<div id="divider3" class="span12">divider3</div>
</div>
<div class="row">
<div id="welcome-news" class="span12">
<div class="row">
<div id="welcome" class="span8"><h2>Name</h2>
<h2>Job title</h2>
<p>Welcome to my site!
Lorem ipsum dolor sit amet, option fabellas mel et, at has doctus noluisse ullamcorper, no facete probatus evertitur
vim. Est id mutat lobortis. Cu ius omnesque apeirian interesset. Quo putent consequuntur at. Mel soluta sadipscing
te. Ea sed impetus patrioque, sed inani vitae ea, sea ne labore prodesset.
Nam in ipsum detracto disputando, sea ei habeo aliquam scripserit, vide simul graeco pri eu. Unum possit ea duo,
maiorum partiendo has ut. Per tamquam omnesque cu. Sed veniam ancillae luptatum te. Sea repudiare euripidis
posidonium ne, ex elit saperet qui.</p></div>
<div id="news" class="span4"><h3>Latest News</h3>
<h4>News Title</h4>
<p>Lorem ipsum dolor sit amet, option fabellas mel et, at has doctus noluisse ullamcorper, no facete probatus evertitur
vim. Est id mutat lobortis. Cu ius omnesque apeirian interesset. Quo putent consequuntur at. Mel soluta sadipscing
te. Ea sed impetus patrioque, sed inani vitae ea, sea ne labore prodesset.
Nam in ipsum detracto disputando, sea ei habeo aliquam scripserit, vide simul graeco pri eu. Unum possit ea duo,
maiorum partiendo has ut. Per tamquam omnesque cu. Sed veniam ancillae luptatum te. Sea repudiare euripidis
posidonium ne, ex elit saperet qui.</p>
<p>dd/mm/yy</p></div>
</div>
</div>
</div>
<!-- Middle end -->
<!-- Footer begin -->
<div class="row">
<div id="divider4" class="span12">divider4</div>
</div>
<div class="row">
<div id="copyright" class="span12"><p>Copyright note</p></div>
</div>
<!-- Footer end -->
</div> <!-- Container end -->
<script src="http://code.jquery.com/jquery.js"></script>
<script src="js/bootstrap.min.js"></script>
</body>
css:
.container { backgound: #28383f;
margin: 0 auto;
width: 940px; }
#divider1a { background: #051d32;
height: 10px;
width: 940px;
margin-left: 30px ;
margin-right: 0px ; }
#divider1b { background: #051d32;
height: 10px;
width: 940px;
margin-left: 30px ;
margin-right: 0px ; }
#logo { background: #28383f;
color: white;
height: 105px;
width: 310px;
margin-right: 0px; }
#socialmedia { background: #28383f;
color: white;
height: 52.5px;
width: 630px;
margin-left: 0px; }
#navbar { background: #28383f;
color: white;
height: 52.5px;
width: 630px;
margin-left: 0px; }
#divider2a { background: #051d32;
height: 10px;
width: 940px;
margin-left: 30px ;
margin-right: 0px ; }
#divider2b { background: #051d32;
height: 10px;
width: 940px;
margin-left: 30px ;
margin-right: 0px ; }
#imgbanner { background: #051d32;
color: white;
height: 340px;
width: 940px;
margin-left: 30px; }
#slidebanner { background: #051d32;
height: 190px;
width: 940px;
margin-left: 30px;
margin-right: 0px; }
#arrowleft { background: #051d32;
color: white;
height: 190px;
width: 110px;
margin-left: 30px;
margin-right: 0px; }
#arrowright { background: #051d32;
color: white;
height: 190px;
width: 110px;
margin-right: 0px;
margin-left: 0px; }
#imgslide { background: #051d32;
color: white;
height: 170px;
width: 170px;
margin-left: 35px;
margin-right: 35px;
margin-top: 10px;
margin-bottom: 10px; }
#divider3 { background: #051d32;
height: 10px;
width: 940px;
margin-left: 30px ;
margin-right: 0px ; }
#welcome-news { margin-left: 120px;
margin-left: 30px; }
#welcome { background: #28383f ;
color: white;
height: 500px;
width: 630px; }
#news { background: #344349;
color: white;
height: 500px;
width: 310px;
margin-left: 0px;
margin-right: 30px; }
#divider4 { background: #051d32;
height: 10px;
width: 940px;
margin-left: 30px ;
margin-right: 0px ; }
#copyright { background: #051d32;
color: white;
height: 50px;
width: 940px;
margin-left: 30px; }
Any help would be greatly appreciated.
Also, you might have noticed in the css code that a lot of the divs have a margin-left: 30px; the page doesn't center properly unless those divs have that 30px left margin for some reason. So any help on that topic would help too. Thanks :)
Edit*
Here's what it looks like in the browser at fullscreen:
http://i1051.photobucket.com/albums/s426/AnimationStudent/breakingproblemsfullscreen_zps57543528.png
And this is what happens when I resize the window:
http://i1051.photobucket.com/albums/s426/AnimationStudent/breakingproblemsresized1_zps4a1d66a0.png
Good to see you trying to learn a new things. MIght I suggest you view tutorials from places such as nettuts+ and a few others as this will deffo help. Also always try to ask questions as that's the only real way you will learn. Now onto your predicament;
Now it seems to me you are trying to establish a static design instead of a responsive design. I assume you want to have it looking the same no matter what screen so try
.container { backgound: #28383f;
margin: 0 auto;
min-width: 940px; !important}
As this with ignore any other sub rulings (even #media ones).
If however you want a responsive design, may I suggest avoid using fixed widths (pixels) and move towards responsive widths(%).
The reason why it might also occur is because your code doest flow. By this I mean you have a span4 and two span8's in the same row. So when the screen shrinks, might be causing the collapsing issue. As regards, to the centring issue...unsure as cannot see a working example so cant tell you why this might be occurring on this design.
Edit*
Based Upon the pictures you have just attached, it seems to be a bit of an unclean and rather cluttered design. By this I mean I do not see the point of the 2 divs and the top or bottom of the header div. Also why are you referring to ids and not classes for styling as on a personal preference I try to avoid using ids as they are better suited towards referencing and classes for styling.