1670943137
In this article, we’ll look at four ways to horizontally and vertically center a div using CSS Grid. Of course, these centering techniques can be used on any kind of element. We’ve previously covered how to center elements horizontally and vertically using Flexbox and positioning with transforms.
Let’s first create a container with a simple box element inside it that we’ll use to demonstrate these centering methods. Here’s the HTML:
<article>
<div></div>
</article>
And here’s our starting CSS:
article {
width: 100%;
min-height: 100vh;
background: black;
display: grid;
}
div {
width: 200px;
background: yellow;
height: 100px;
}
In all our examples, we’ll be using the display: grid
property. This establishes the <article>
element as a grid container and generates a block-level grid for that container. (Here’s our demo template on CodePen if you want to experiment with it.)
Now, let’s look at the various ways to center our div.
My favorite way to center an element with Grid is to use the place-self
property. (You can read more about it here.)
Centering our div is as simple as this:
article {
display: grid;
}
div {
place-self: center;
}
The place-self
property is a shorthand for the align-self
(vertical) and justify-self
(horizontal) properties (which are useful if you’re just centering along one axis). You can experiment with them in this CodePen demo.
Using place-self
is so simple that it’s an obvious go-to solution. But it’s not the only way to center an element with Grid, so let’s now look at some other methods.
An advantage of using place-self
is that it’s applied to the element being centered, meaning that you can also use it to center other elements in the same container. (Try adding more div elements to the CodePen demo and see what happens.)
Let’s now look at what’s involved with using Grid with justify-content
and align-items
to center our div.
The justify-content
property is used to align the container’s items horizontally when the items don’t use all the available space. There are many ways to set the justify-content
property, but here we’re just going to set it to center
.
Just like the justify-content
property, the align-items
property is used to align the content in a container, but it aligns content vertically rather than horizontally.
Let’s return to our test HTML and add the following code to the parent container:
article {
display: grid;
justify-content: center;
align-items: center;
}
An apparent advantage of this method is that it involves less code, as the centering is handled by the container. But in some ways it’s also a disadvantage to target the div via its container, as any other element in the container will also be affected.
As always, we’ll target the parent container with display: grid
. We’ll also assign the div an automatic margin using margin: auto
. This makes the browser automatically calculate the available space surrounding the child div and divide it vertically and horizontally, placing the div in the middle:
article {
display: grid;
}
div {
margin: auto;
}
(As an aside, there are lots of other cool things you can do with CSS margins.)
The place-items
property is used to align items vertically and horizontally in a grid. It can be used to center our div by targeting the container like this:
article {
display: grid;
place-items: center;
}
Like the place-self
property, place-items
is shorthand for two properties, in this case justify-items
(horizontal) and align-items
(vertical). You can experiment with them in this CodePen demo.
In contrast to place-self
, place-items
is applied to the container, which gives it slightly less flexibility.
Each of these methods lets you center a div horizontally and vertically within a container. As I said, my preference is the the place-self
method, mainly because it’s applied to the element being centered rather than the container. That’s the same for the margin: auto
method. But of course, if you’re only looking to center your element in one direction, you can also use either align-self
or justify-self
.
In the demo examples, we’ve just used an empty div, but of course you can add content to the div and the centering will still work. And, once again, these centering techniques work on elements other than divs.
Further reading:
Original article source at: https://www.sitepoint.com/
1667380096
In this tutorial, we will learn how to detect mouse / touch hold with HTML, CSS and JavaScript. Learn how to detect mouse / touch hold using HTML, CSS and JavaScript.
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Detect Mouse/Touch Hold</title>
<!-- Stylesheet -->
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div class="container">
<div id="div-ref">Hold Mouse Here</div>
<p id="result">Demo Text Here</p>
</div>
<!-- Script -->
<script>
//Create Initial References
let divRef = document.getElementById("div-ref");
let result = document.getElementById("result");
let isMouseHold = true;
let timeoutref;
let deviceType = "";
//Events Object
let events = {
mouse: {
down: "mousedown",
up: "mouseup",
},
touch: {
down: "touchstart",
up: "touchend",
},
};
//Detect if the device is a touch device
const isTouchDevice = () => {
try {
//We try to create Touch Event (It would fail for desktops and throw error)
document.createEvent("TouchEvent");
deviceType = "touch";
return true;
} catch (e) {
deviceType = "mouse";
return false;
}
};
isTouchDevice();
//Function on mouse down
divRef.addEventListener(events[deviceType].down, (e) => {
e.preventDefault();
isMouseHold = true;
//Mouse down will be considered mouse hold if it is being held down for more than 1500ms
timeoutref = setTimeout(function () {
//If mouse is being held down do this
if (isMouseHold) {
result.innerText = "Mouse is being held down";
}
}, 1500);
});
//Function on mouse up
//If mouse is released do this
divRef.addEventListener(events[deviceType].up, function () {
//Clear the timeout
clearTimeout(timeoutref);
result.innerText = "Mouse hold is released";
});
</script>
</body>
</html>
* {
padding: 0;
margin: 0;
box-sizing: border-box;
font-family: "Poppins", sans-serif;
}
body {
background-color: #fec04f;
}
.container {
height: 31.25em;
width: 31.25em;
background-color: #151515;
position: absolute;
transform: translate(-50%, -50%);
top: 50%;
left: 50%;
display: flex;
align-items: center;
justify-content: space-around;
flex-direction: column;
border-radius: 0.5em;
padding: 0 1.5em;
text-align: center;
box-shadow: 0 2em 4em rgba(84, 58, 11, 0.4);
}
#div-ref {
font-size: 1.6em;
height: 12em;
width: 12em;
background-color: #ffd68b;
border-radius: 50%;
display: grid;
place-items: center;
user-select: none;
font-weight: 300;
line-height: 1.8em;
}
p {
font-size: 1.2em;
width: 100%;
background-color: rgba(255, 255, 255, 0.2);
padding: 0.8em 0;
color: #ffffff;
border-radius: 0.5em;
}
We implement the functionality using javascript. Now copy the code below and paste it into your script file. We add the logic to our project in the following steps:
#html #css #javascript
1654612620
このチュートリアルでは、divの背景画像を取得する方法、divの背景画像を設定する方法、jQueryを使用して背景画像をdivで削除する方法を学習します。
ここでは、jQueryを使用して背景画像を取得、設定、削除する手順を学びます。
以下のコードを使用して、jQueryで背景画像を取得できます。
$(".btn-get").click(function() {
var bg = $('div').css('background-image'); // get background image using css property
bg = bg.replace('url(','').replace(')','');
alert(bg);
});
以下のコードを使用して、jQueryCSSプロパティを使用して背景画像を設定できます。
$(".btn-set").click(function() {
var img = '//www.tutsmake.com/wp-content/uploads/2019/08/How-to-Encode-Decode-a-URL-Using-JavaScript.jpeg';
var bg = $('div').css('background-image',"url(" + img + ")");
});
以下のコードを使用して、jQueryCSSプロパティを使用して背景画像を削除できます。
$(".btn-remove").click(function() {
var bg = $('div').css('background-image','none');
});
ここでは例を取り上げます。この例では、divの背景画像を取得し、背景画像を設定し、jQuerycssプロパティを使用して背景画像を削除/削除します。
<html>
<head>
<title> How to get, set and remove background image attribute example</title>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
$(function() {
$(".btn-get").click(function() {
var bg = $('#bg-img').css('background-image');
bg = bg.replace('url(','').replace(')','');
alert(bg);
});
$(".btn-remove").click(function() {
var bg = $('#bg-img').css('background-image','none');
});
$(".btn-set").click(function() {
var img = '//www.tutsmake.com/wp-content/uploads/2019/08/How-to-Encode-Decode-a-URL-Using-JavaScript.jpeg';
var bg = $('#bg-img').css('background-image',"url(" + img + ")");
});
});
</script>
<style>
.card{
margin: 30px;
}
</style>
</head>
<body>
<div class="card">
<div id="bg-img" style="background-image: url('//www.tutsmake.com/wp-content/uploads/2019/08/How-to-Download-Install-XAMPP-on-Windows.jpeg'); width: 1000px; height: 500px;">
</div>
</div>
<button type="type" class="btn-get">Get background image</button>
<button type="type" class="btn-set">Set background image</button>
<button type="type" class="btn-remove">Remove background image</button>
</body>
</html>
この記事では、jQuery CSSプロパティを使用して背景画像を取得、設定、および削除する方法を学習しました。
このストーリーは、もともとhttps://www.tutsmake.com/get-set-and-delete-div-background-image-in-jquery/で公開されました
1654612020
En este tutorial, aprenderá cómo obtener una imagen de fondo div, cómo configurar la imagen de fondo div y cómo eliminar la imagen de fondo div usando jQuery.
Aquí aprenderá paso a paso, obtener, configurar y eliminar la imagen de fondo usando jQuery.
Puede usar el siguiente código para obtener la imagen de fondo en jQuery.
$(".btn-get").click(function() {
var bg = $('div').css('background-image'); // get background image using css property
bg = bg.replace('url(','').replace(')','');
alert(bg);
});
Puede usar el siguiente código para configurar la imagen de fondo usando la propiedad jQuery CSS.
$(".btn-set").click(function() {
var img = '//www.tutsmake.com/wp-content/uploads/2019/08/How-to-Encode-Decode-a-URL-Using-JavaScript.jpeg';
var bg = $('div').css('background-image',"url(" + img + ")");
});
Puede usar el siguiente código para eliminar la imagen de fondo usando la propiedad jQuery CSS.
$(".btn-remove").click(function() {
var bg = $('div').css('background-image','none');
});
Aquí tomaremos un ejemplo, en este ejemplo obtendremos la imagen de fondo div, estableceremos la imagen de fondo y eliminaremos/eliminaremos la imagen de fondo usando la propiedad jQuery css
<html>
<head>
<title> How to get, set and remove background image attribute example</title>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
$(function() {
$(".btn-get").click(function() {
var bg = $('#bg-img').css('background-image');
bg = bg.replace('url(','').replace(')','');
alert(bg);
});
$(".btn-remove").click(function() {
var bg = $('#bg-img').css('background-image','none');
});
$(".btn-set").click(function() {
var img = '//www.tutsmake.com/wp-content/uploads/2019/08/How-to-Encode-Decode-a-URL-Using-JavaScript.jpeg';
var bg = $('#bg-img').css('background-image',"url(" + img + ")");
});
});
</script>
<style>
.card{
margin: 30px;
}
</style>
</head>
<body>
<div class="card">
<div id="bg-img" style="background-image: url('//www.tutsmake.com/wp-content/uploads/2019/08/How-to-Download-Install-XAMPP-on-Windows.jpeg'); width: 1000px; height: 500px;">
</div>
</div>
<button type="type" class="btn-get">Get background image</button>
<button type="type" class="btn-set">Set background image</button>
<button type="type" class="btn-remove">Remove background image</button>
</body>
</html>
En este artículo, ha aprendido cómo obtener, establecer y eliminar una imagen de fondo utilizando la propiedad jQuery CSS.
Esta historia se publicó originalmente en https://www.tutsmake.com/get-set-and-delete-div-background-image-in-jquery/
1651316640
Hay algunos problemas de codificación comunes que puede encontrar cuando comienza a practicar lo que ha aprendido mediante la creación de proyectos.
Un problema común que enfrentará como desarrollador web es cómo colocar un elemento en el centro de una página o dentro de un elemento que actúe como su contenedor. Es el omnipresente "¿Cómo centro un div?" problema.
En este artículo, veremos cómo podemos centrar elementos usando varias propiedades CSS. Veremos ejemplos de código en cada sección y una representación visual de los elementos en todos los ejemplos.
En esta sección, veremos cómo podemos usar la propiedad CSS Flexbox para centrar un elemento horizontalmente, verticalmente y en el centro de una página/contenedor.
Puede usar una imagen si lo prefiere, pero solo usaremos un círculo simple dibujado con CSS. Aquí está el código:
<div class="container">
<div class="circle">
</div>
</div>
.container {
width: 500px;
height: 250px;
margin: 50px;
outline: solid 1px black;
}
.circle {
width: 50px;
height: 50px;
border-radius: 50%;
background-color: black;
}
El posicionamiento con Flexbox requiere que escribamos el código en la clase del elemento padre o contenedor.
Ahora escribiremos el código para centrar el div
elemento horizontalmente. Todavía estamos haciendo uso del círculo que creamos arriba.
.container {
width: 500px;
height: 250px;
margin: 50px;
outline: solid 1px black;
display: flex;
justify-content: center;
}
.circle {
width: 50px;
height: 50px;
border-radius: 50%;
background-color: black;
}
Agregamos dos líneas de código para centrar el círculo horizontalmente. Estas son las líneas que agregamos:
display: flex;
justify-content: center;
display: flex;
nos permite usar Flexbox y sus propiedades, mientras justify-content: center;
alinea el círculo al centro horizontalmente.
Aquí está la posición de nuestro círculo:
Lo que haremos en esta sección es similar a la anterior, excepto por una línea de código.
.container {
width: 500px;
height: 250px;
margin: 50px;
outline: solid 1px black;
display: flex;
align-items: center;
}
.circle {
width: 50px;
height: 50px;
border-radius: 50%;
background-color: black;
}
En este ejemplo, solíamos align-items: center;
centrar el círculo verticalmente. Recuerde que estamos obligados a escribir display: flex;
primero antes de especificar la dirección.
Aquí está la posición de nuestro círculo:
En esta sección, colocaremos el círculo en el centro de la página usando las propiedades de alineación horizontal y vertical de CSS Flexbox. Así es cómo:
.container {
width: 500px;
height: 250px;
margin: 50px;
outline: solid 1px black;
display: flex;
justify-content: center;
align-items: center;
}
.circle {
width: 50px;
height: 50px;
border-radius: 50%;
background-color: black;
}
Aquí están las tres líneas de código que agregamos a la clase de contenedor anterior:
display: flex;
justify-content: center;
align-items: center;
Como era de esperar, comenzamos con display: flex;
lo que nos permite usar Flexbox en CSS. Luego usamos las propiedades justify-content
(alineación horizontal) y align-items
(alineación vertical) para colocar el círculo en el centro de la página.
Aquí está la posición de nuestro círculo:
margin
propiedad CSSEn esta sección, usaremos la margin
propiedad para centrar nuestro círculo horizontalmente.
Vamos a crear nuestro círculo de nuevo.
<div class="container">
<div class="circle">
</div>
</div>
.container {
width: 500px;
height: 250px;
margin: 50px;
outline: solid 1px black;
}
.circle {
width: 50px;
height: 50px;
border-radius: 50%;
background-color: black;
}
Esta vez escribiremos el código en la circle
clase. Así es cómo:
.container {
width: 500px;
height: 250px;
margin: 50px;
outline: solid 1px black;
}
.circle {
width: 50px;
height: 50px;
border-radius: 50%;
background-color: black;
margin: 0 auto;
}
Todo lo que hemos agregado es la margin: 0 auto;
línea de código a la circle
clase.
Echemos un vistazo a la posición del círculo:
text-align
propiedad CSSEn esta sección, veremos cómo centrar el texto horizontalmente.
Este método solo funciona cuando estamos trabajando con texto escrito dentro de un elemento.
Aquí hay un ejemplo:
<div class="container">
<h1>Hello World!</h1>
</div>
En el ejemplo anterior, hemos creado un div
con una clase de contenedor y un h1
elemento con algo de texto. Así es como se ve en este momento:
Escribamos el código CSS.
.container {
width: 500px;
height: 250px;
margin: 50px;
outline: solid 1px black;
}
h1 {
text-align: center;
}
En otro, para alinear el texto en el h1
elemento en el centro de la página, tuvimos que usar la text-align
propiedad, dándole un valor de center
. Así es como se ve ahora en el navegador:
En este artículo, vimos cómo podemos centrar elementos horizontalmente, verticalmente y en el centro de la página usando Flexbox y las propiedades margin y text-align en CSS.
En cada sección, vimos un ejemplo de código y una representación visual de lo que hace el código.
¡Feliz codificación!
Fuente: https://www.freecodecamp.org/news/how-to-center-a-div-with-css/
1651231980
プロジェクトの構築によって学んだことを実践し始めるときに遭遇する可能性のある、いくつかの一般的なコーディングの問題があります。
Web開発者として直面する一般的な問題の1つは、要素をページの中央に配置する方法、またはそのコンテナーとして機能する要素内に配置する方法です。それはどこにでもある「どうすればdivを中央に配置できますか?」です。問題。
この記事では、さまざまなCSSプロパティを使用して要素を中央に配置する方法を説明します。各セクションにコード例があり、すべての例の要素が視覚的に表現されています。
このセクションでは、CSS Flexboxプロパティを使用して、要素を水平方向、垂直方向、およびページ/コンテナーの中央に配置する方法を説明します。
必要に応じて画像を使用できますが、CSSで描画された単純な円を使用します。コードは次のとおりです。
<div class="container">
<div class="circle">
</div>
</div>
.container {
width: 500px;
height: 250px;
margin: 50px;
outline: solid 1px black;
}
.circle {
width: 50px;
height: 50px;
border-radius: 50%;
background-color: black;
}
Flexboxを使用して配置するには、親要素またはコンテナ要素のクラスにコードを記述する必要があります。
div
次に、要素を水平方向に中央揃えするコードを記述します。上で作成した円を引き続き使用しています。
.container {
width: 500px;
height: 250px;
margin: 50px;
outline: solid 1px black;
display: flex;
justify-content: center;
}
.circle {
width: 50px;
height: 50px;
border-radius: 50%;
background-color: black;
}
円を水平方向に中央揃えするために2行のコードを追加しました。追加した行は次のとおりです。
display: flex;
justify-content: center;
display: flex;
Flexboxとそのプロパティを使用しながらjustify-content: center;
、円を水平方向に中央に揃えることができます。
これが私たちのサークルの位置です:
このセクションで行うことは、1行のコードを除いて、前のセクションと同様です。
.container {
width: 500px;
height: 250px;
margin: 50px;
outline: solid 1px black;
display: flex;
align-items: center;
}
.circle {
width: 50px;
height: 50px;
border-radius: 50%;
background-color: black;
}
この例ではalign-items: center;
、円を垂直方向に中央に配置するために使用しました。display: flex;
方向を指定する前に、最初に書き込む必要があることを思い出してください。
これが私たちのサークルの位置です:
このセクションでは、CSS Flexboxの水平方向と垂直方向の両方の配置プロパティを使用して、円をページの中央に配置します。方法は次のとおりです。
.container {
width: 500px;
height: 250px;
margin: 50px;
outline: solid 1px black;
display: flex;
justify-content: center;
align-items: center;
}
.circle {
width: 50px;
height: 50px;
border-radius: 50%;
background-color: black;
}
上記のコンテナクラスに追加した3行のコードは次のとおりです。
display: flex;
justify-content: center;
align-items: center;
予想通り、display: flex;
CSSでFlexboxを使用できるようにすることから始めます。次に、justify-content
(水平方向の配置)プロパティとalign-items
(垂直方向の配置)プロパティの両方を使用して、円をページの中央に配置しました。
これが私たちのサークルの位置です:
margin
このセクションでは、margin
プロパティを使用して円を水平方向に中央揃えします。
もう一度サークルを作りましょう。
<div class="container">
<div class="circle">
</div>
</div>
.container {
width: 500px;
height: 250px;
margin: 50px;
outline: solid 1px black;
}
.circle {
width: 50px;
height: 50px;
border-radius: 50%;
background-color: black;
}
今回はcircle
クラスにコードを記述します。方法は次のとおりです。
.container {
width: 500px;
height: 250px;
margin: 50px;
outline: solid 1px black;
}
.circle {
width: 50px;
height: 50px;
border-radius: 50%;
background-color: black;
margin: 0 auto;
}
追加したのは、クラスmargin: 0 auto;
へのコード行だけです。circle
円の位置を見てみましょう。
text-align
このセクションでは、テキストを水平方向に中央揃えする方法を説明します。
このメソッドは、要素内に記述されたテキストを操作している場合にのみ機能します。
次に例を示します。
<div class="container">
<h1>Hello World!</h1>
</div>
上記の例ではdiv
、コンテナのクラスとh1
テキストを含む要素を使用してを作成しました。現時点では次のようになっています。
CSSコードを書いてみましょう。
.container {
width: 500px;
height: 250px;
margin: 50px;
outline: solid 1px black;
}
h1 {
text-align: center;
}
h1
その他、ページの中央にある要素のテキストを揃えるには、text-align
プロパティを使用して値を.にする必要がありcenter
ました。ブラウザでの表示は次のとおりです。
この記事では、FlexboxとCSSのmarginおよびtext-alignプロパティを使用して、要素を水平方向、垂直方向、およびページの中央に中央揃えする方法を説明しました。
各セクションでは、コード例とコードの機能の視覚的表現の両方を見ました。
ハッピーコーディング!
ソース:https ://www.freecodecamp.org/news/how-to-center-a-div-with-css/
1625050440
Live demo: https://bitesizeacademy.github.io/
The source code for this video: https://github.com/bitesizeacademy/react-drag-and-drop
In this video we look at how to drag and drop in react using the react-use-gesture and react-spring libraries. We take the introduction screen of create-react-app and add dragging to its components. We then add an overlay which can be dragged up and down to expose a background image behind it. We use the hooks: useDrag (from react-use-gesture) and useSpring (from react-spring).
My previous video about react-spring: How to animate mount and unmount of a react component using react-spring https://www.youtube.com/watch?v=kT6yYSwK1oA
https://react-spring.io/
https://use-gesture.netlify.app/
Background image by Adam Vradenburg @vradenburg https://unsplash.com/photos/_gu7E90QChU
#react #animate #javascript
#div #react