Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <main>
	<h1>How Background Position Works</h1>
	
	<form id="size">
		<button type="button" class="is-active">auto 100%</button>
		<button type="button">cover</button>
		<br><br>
		<label for="form-name">Custom <code>background-size</code>:</label><br>
		<input id="form-name" type="text" name="custom" value="auto 100%">
	</form>
	
	<form id="position">
		<input id="range" type="range" min="0" max="100" value="0">
		<input id="range-output" type="text" value="0" readonly>
	</form>
	
	<div id="demo-background"></div>
	
	<div id="demo-img">
		<img src="https://images.unsplash.com/photo-1555685812-4b943f1cb0eb?ixlib=rb-1.2.1&q=85&fm=jpg&crop=entropy&cs=srgb&ixid=eyJhcHBfaWQiOjE0NTg5fQ" alt="">
	</div>

	<h2>References</h2>
	<ul>
		<li><a href="https://developer.mozilla.org/en-US/docs/Web/CSS/background-position" target="_blank" rel="noopener">MDN: background-position</a></li>
		<li><a href="https://blogs.adobe.com/creativecloud/a-primer-to-background-positioning-in-css/" target="_blank" rel="noopener">Adobe: “A Primer To Background Positioning In CSS” by Sara Soueidan</a></li>
	</ul>
</main>

              
            
!

CSS

              
                html {
	box-sizing: border-box;
}

*,
::after,
::before {
	box-sizing: inherit;
}

body {
	margin: 1rem auto 3rem;
	line-height: 1.4;
	tab-size: 4;
}

main {
	display: block; /* Fix IE rendering main as inline */
	margin: 0 auto;
	max-width: 42rem;
	padding-left: 1rem;
	padding-right: 1rem;
}

img {
	display: block;
	max-width: 100%;
}

form {
	margin-bottom: 1rem;
}

button {
	border: 1px solid black;
}

button.is-active {
	background-color: blue;
	color: white;
}

/* https://codepen.io/jakob-e/pen/YbrRYN */
#demo-img,
#demo-background {
  width: 100vw;
	height: 300px;
  margin-right: calc(50% - 50vw);
  margin-left: calc(50% - 50vw);
	background-color: #eee;
	user-select: none;
}

#demo-background {
	background-image: url('https://images.unsplash.com/photo-1555685812-4b943f1cb0eb?ixlib=rb-1.2.1&q=85&fm=jpg&crop=entropy&cs=srgb&ixid=eyJhcHBfaWQiOjE0NTg5fQ');
	background-size: auto 100%; /* cover */
	background-position: 0% 50%; /* 20% 50% */
	background-repeat: no-repeat;
}

#demo-img {
	position: relative;
	overflow: hidden;
}

#demo-img img {
	position: absolute;
	top: 50%;
 	left: 0%; /* 20% */
	transform: translateY(-50%);
	width: auto; /* 100% */
	height: 100%;
	object-fit: cover;
}

              
            
!

JS

              
                var background = document.querySelector('#demo-background');
var img = document.querySelector('#demo-img img');
var rangeOutput = document.querySelector('#range-output');

/**
 * Upate image sizes based on form input.
 * @param  {String} value
 * @return {void}
 */
function updateImageSizes(value) {
	// Update background
	background.style['background-size'] = value;

	// Update image
	var wh = value.split(' ');
	if (wh.length === 2) {
		img.style.width = wh[0];
		img.style.height = wh[1];
	} else {
		img.style.width = '100%';
		img.style.height = '100%';
	}
}

/**
 * QSA = "Query Selector All" that returns an Array instead of a NodeList.
 * @param  {String}   selector
 * @param  {Element}  context
 * @return {Array}
 */
function qsa(selector) {
  var context = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : document;
  return Array.prototype.slice.call(context.querySelectorAll(selector));
}

/**
 * Return the index for a given element.
 * @param  {Element}  elem
 * @return {Number}
 */
function getIndex(elem) {
  var i = 0;
  while ((elem = elem.previousElementSibling)) i++;
  return i;
}

/**
 * Is element a button?
 * @param  {Element}
 * @return {Boolean}
 */
function isButton(elem) {
	return elem.tagName === 'BUTTON';
}

/**
 * Is event an arrow key?
 * @param  {Event}
 * @return {Boolean}
 */
function isArrowKey(event) {
	return [
		'ArrowLeft',
		'ArrowRight',
		'ArrowUp',
		'ArrowDown',
	].indexOf(event.key) >= 0;
}

/**
 * Init form to customize image properties.
 * @param  {Element} form
 * @param  {Object}  params
 * @return {void}
 */
function initForm(form, params) {
	var input = form.querySelector('input[name="custom"]');
	var buttons = qsa('button[type="button"]', form);
	var buttonValues = buttons.map(function (button) { return button.innerText; });

	/**
	 * Reset button states.
	 * @return {void}
	 */
	function resetButtons() {
		buttons.forEach(function (button) {
			button.classList.remove('is-active');
		});
	}

	// Buttons
	form.addEventListener('click', function (event) {
		// Only watch buttons
		if (!isButton(event.target)) {
			return;
		}

		var button = event.target;
		var value = button.innerText;

		updateImageSizes(value);
		resetButtons();
		
		event.preventDefault();
		button.focus();
		button.classList.add('is-active');
		input.value = value;
	});

	// // Auto-click focused buttons
	// form.addEventListener('focusin', function (event) {
	// 	// Only watch buttons
	// 	if (!isButton(event.target)) {
	// 		return;
	// 	}
	// 
	// 	event.target.click();
	// });
	
	// Custom input
	input.addEventListener('input', function (event) {
		var value = input.value;
		var match = buttonValues.indexOf(value);
		
		updateImageSizes(value);
		resetButtons();
		
		if (!value) {
			buttons[0].classList.add('is-active');
		} else if (match >= 0) {
			buttons[match].classList.add('is-active');
		}
	});
}

initForm(size, { prop: 'background-size' });

// Arrow keys - size
var sizeButtons = qsa('button[type="button"]', size);
size.addEventListener('keydown', function (event) {
	// Only watch arrow keys on buttons
	if (!isButton(event.target) || !isArrowKey(event)) {
		return;
	}
	
	var button = event.target;
	var index = getIndex(button);
	var nextIndex = index;
	var numButtons = sizeButtons.length;
	
	event.preventDefault();
	
	if (event.key === 'ArrowLeft') {
		nextIndex -= 1;
	} else if (event.key === 'ArrowRight') {
		nextIndex += 1;
	}

	if (nextIndex < 0) {
		nextIndex += numButtons;
	} else if (nextIndex >= numButtons) {
		nextIndex -= numButtons;
	}
	
	var nextButton = sizeButtons[nextIndex];
	nextButton.click();
});

// ------------------------------
// Position range
// ------------------------------

// Watch range
position.addEventListener('input', function (event) {
	var x = (event.target.value || 0) + '%';
	background.style.backgroundPosition = x + '50%';
	img.style.left = x;
	rangeOutput.value = x;
});

              
            
!
999px

Console