frontpage.css

body {
	background: url('Background.jpg');
}
box1 {
	position: absolute;
	left: 100px;
	top: 100px;
}
box2 {
	top: 100px;
	position: absolute;
	right: 100px;
}

index.php

<body>

<div id="box1"><img src="Customer Goods.jpg" /></div>

<div id="box2"><img src="Industry.jpg" /></div>

</body>

Hey, I would like to create 2 boxes next to each other in my index.php using css. What happen with this code is: The boxes align to the left and on top of each other.

This is strange why the actual is not the same as I coded? I thought it should be 100 px from the top of the web site (both of them), and 1 box 100 px from the left side of the website, where as the other 100 px from the right of the website.

Where is the logic in this codes?

Dani AI

Generated

Brief expert summary and troubleshooting notes tied to the replies below.

As described, the two image containers are ending up stacked and left-aligned. correctly pointed out a selector problem in the thread, and both and raised sizing and spacing considerations. Beyond those fixes, run a short checklist with the browser devtools: confirm the stylesheet is actually loaded (Network tab), verify the CSS rules are applied to the intended elements (Elements / Computed styles), and add temporary outlines or background colors so the boxes are visible while testing. Check image filenames for spaces or unexpected characters, since those can break links on some servers.

If absolute positioning is kept, remember the positioned box is placed relative to its nearest ancestor that has a position other than static; otherwise it uses the viewport. In many cases absolute positioning is brittle for layout; a more robust approach is to let the container handle horizontal placement. Using flexbox is simple and responsive: put the two boxes in a wrapper and let the wrapper distribute space. Example pattern:

<div class="row">
  <div class="box">...</div>
  <div class="box">...</div>
</div>

/* .row uses flexbox to line the boxes up horizontally and space them */

See the CSS position and flexbox references for precise behavior and examples: CSS position on MDN and Basic concepts of Flexbox on MDN.

Final notes: give images display: block when inside a container, define sensible max-widths for responsiveness, and clear cache when testing stylesheet changes.

Recommended Answers

All 3 Replies

Assign Width to each box may be that would help.

You also haven't indicated in the css that box1 and box2 belong to IDs

body {
	background: url('Background.jpg');
}
#box1 {
	position: absolute;
	left: 100px;
	top: 100px;
}
#box2 {
	top: 100px;
	position: absolute;
	right: 100px;
}

You can also use padding to control distance

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.